Null Reference Exception Error

Hi,

I wrote two scripts to handle health in my game.
One for my player to have Health and one for enemies to deal damage to my player.

In my DealDamage function it seems that Unity can’t find the playerHealth.currentHealth call. It only gives back a Null Reference Exception Error.

I can not find out what I did wrong. :frowning:

My PlayerHealth Script:

using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour 
{
	public int startingHealth;
	public int currentHealth;
	public GameObject playerExplosion;

	private GameController gameController;
	private bool isDead;


	void Start()
	{
		isDead = false;
		GameObject gameControllerObject = GameObject.FindWithTag("GameController");
		if (gameControllerObject !=null)
		{
			gameController = gameControllerObject.GetComponent<GameController>();
		}
		if(gameController == null)
		{
			Debug.Log("Cannot find 'GameController' script");
		}
	}


	void Awake()
	{
		currentHealth = startingHealth;
	}

	public void TakeDamage(int amount)
	{
		currentHealth -= amount;

		if (currentHealth <= 0 && !isDead) 
		{
			Death ();
		}

	}

	void Death()
	{
		isDead = true;
		Destroy (gameObject);
		Instantiate (playerExplosion, transform.position, transform.rotation);
		gameController.GameOver();

	}
}

and my EnemyHit Script:

using UnityEngine;
using System.Collections;

public class EnemyHit : MonoBehaviour 
{
	public int attackDamage;

	GameObject player;
	PlayerHealth playerHealth;


	void Start()
	{
		player = GameObject.FindGameObjectWithTag ("Player");
		playerHealth = player.GetComponent<PlayerHealth> ();
	}

	void OnTriggerEnter(Collider other)
	{
		if (other.gameObject == player) 
		{
			DealDamage ();
		}
	}

	void DealDamage()
	{
		if (playerHealth.currentHealth > 0) 
		{
			playerHealth.TakeDamage (attackDamage);
		}
	}
}

I can guess this:

  1. Your EnemyHit is disabled while the GameObject (who attaching EnemyHit), which prevent EnemyHit’s Start function be called first. please note that according to the docs, OnTriggerEnter still be called even your script is disabled, so to avoid headaches, make sure you have EnemyHit enabled or…

    void DealDamage()
    {
    	if(!playerHealth)
    	{
    		Start();
    		if(!playerHealth)
    			Debug.LogError("PlayerHealth not found, go to solution 2");
    	}
    	if (playerHealth.currentHealth > 0) 
    	{
    		playerHealth.TakeDamage (attackDamage);
    	}
    }
    
  2. Make sure that ONLY your player has tag “player”, unfortunely, there is no quick solution for this*, so you need to iterate/check every of gameobject in your scene whenever any other gameobject accidentally tagged as “player”. or see a (not quick) solution here

PS : This can be a good Feature request :slight_smile: