NullReferenceException

Hey. Im following this tutorial and new to unity. I have added some scripts for the enemy to lose health when hit with a player laser. I have these two scripts attached to the enemy object but I get this error when I try to run it

NullReferenceException: Object reference not set to an instance of an object
Enemies.EnemyHit (Damage damageDealer) (at Assets/Scripts/Enemies.cs:29)
Enemies.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Enemies.cs:24)

Enemies class

  • public class Enemies : MonoBehaviour
  • {
  • [SerializeField] int health = 100;
    • private void OnTriggerEnter2D(Collider2D other)
  • {
  • Damage damageDealer = other.gameObject.GetComponent();
  • EnemyHit(damageDealer);
  • }
    • private void EnemyHit(Damage damageDealer)
  • {
  • health -= damageDealer.GetDamage();
    • if (health <= 0)
  • {
  • Destroy(gameObject);
  • }
  • }
    • }

Damage class

    • public class Damage : MonoBehaviour
  • {
  • [SerializeField] int damage = 100;
    • public int GetDamage()
  • {
  • return damage;
  • }
    • public void Hit()
  • {
  • Destroy(gameObject);
  • }
    • }

I’ve tracked the error down to damagedealer.GetDamage(). If anyone can see the problem any help would be greatly appreciated.

  • Please use Code-Tags when posting code and not plain-text

  • The error tells you which line and even which column the error is on (we can’t tell you that because we don’t see the lines as it’s plain-text)

  • NullReferenceException is therefore telling you that you’re referring to an object that doesn’t exist and the error even tells you the exact point in the code

If you follow the above you’d soon find the issue. Most likely you’re getting a component (Damage) that isn’t there then immediately call stuff on it without checking if it’s NULL. As the docs state, GetComponent will return NULL if the component isn’t there and you’re just assuming it will be.