Player Health Tracking

From STEAMwiki
Jump to: navigation, search

Create a scene and call it "game over". Open the File->Build Settings to add that scene to the "scenes in build" list.

Now we need to create a variable on our player to keep track of the player's health. Add a script to your player called "PlayerHealth".

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerHealth : MonoBehaviour {
    public int PlayerHealthNumber = 100;
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

Add the tag "Player" to the gameobject representing the player. Next, let's assume that there is an enemy projectile shooting at the player. Add a new script "enemyShot" to that enemy projectile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class enemyShot : MonoBehaviour
{

	// Use this for initialization
	void Start()
	{

	}

	// Update is called once per frame
	void Update()
	{

	}

	void OnCollisionEnter(Collision col)
	{
		// Debug.Log(gameObject.name + " collided with " + col.gameObject.name);
		if (col.gameObject.tag == "Player")
		{
			PlayerHealth PlayerHealthScript = col.gameObject.GetComponentInChildren<PlayerHealth>();
			PlayerHealthScript.PlayerHealthNumber = PlayerHealthScript.PlayerHealthNumber - 40;

			Debug.Log(PlayerHealthScript.PlayerHealthNumber);

			if (PlayerHealthScript.PlayerHealthNumber <= 0)
			{
				SceneManager.LoadScene("game over");
			}
			
		}
	}

}

Next, you can create a UI element to display the player's health.