NullReferenceException: Object reference not set to an instance of an object EnemyScript

Hi guys, I’m new to Unity and I have been getting an error “NullReferenceException: Object reference not set to an instance of an object
EnemyScript.Update () (at Assets/Scripts/EnemyScript.cs:33)” Don’t know what I’m doing wrong. Please help out?

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

public class EnemyScript : MonoBehaviour
{
    private float range;
    private Transform target;
    private float minDistance = 5.0f;
    private bool targetCollision = false;
    private float speed = 2.0f;
    private float thrust = 1.5f;
    public float health = 5;
    private int hitStrength = 10;

    public Sprite deathSprite;
    public Sprite[] sprites;

    private GameManager gameManager;

    private bool isDead = false;
    void Start()
    {
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
        int rnd = Random.Range(0, sprites.Length);
        GetComponent<SpriteRenderer>().sprite = sprites[rnd];
        target = GameObject.Find("Player").transform;
        health += (0.1f * gameManager.GetLevel());
    }

    void Update()
    {
        range = Vector2.Distance(transform.position, target.position);
        if(range < minDistance && !isDead)
        {
            if (!targetCollision)
            {
                // Get the position of the player
                transform.LookAt(target.position);

                // Correct the rotation
                transform.Rotate(new Vector3(0, -90, 0), Space.Self);
                transform.Translate(new Vector3(speed * Time.deltaTime, 0, 0));
            }
        }
        transform.rotation = Quaternion.identity;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player") && !targetCollision)
        {
            Vector3 contactPoint = collision.contacts[0].point;
            Vector3 center = collision.collider.bounds.center;

            targetCollision = true;

            bool right = contactPoint.x > center.x;
            bool left = contactPoint.x < center.x;
            bool top = contactPoint.y > center.y;
            bool bottom = contactPoint.y < center.y;

            if (right) GetComponent<Rigidbody2D>().AddForce(transform.right * thrust, ForceMode2D.Impulse);
            if (left) GetComponent<Rigidbody2D>().AddForce(-transform.right * thrust, ForceMode2D.Impulse);
            if (top) GetComponent<Rigidbody2D>().AddForce(transform.up * thrust, ForceMode2D.Impulse);
            if (bottom) GetComponent<Rigidbody2D>().AddForce(-transform.up * thrust, ForceMode2D.Impulse);
            Invoke("FalseCollision", 0.5f);
        }
    }

    void FalseCollision()
    {
        targetCollision = false;
        GetComponent<Rigidbody2D>().velocity = Vector3.zero;
    }

    public void TakeDamage(float amount)
    {
        health -= amount;
        if(health < 0)
        {
            isDead = true;
            GetComponent<Rigidbody2D>().velocity = Vector3.zero;
            GetComponent<SpriteRenderer>().sprite = deathSprite;
            GetComponent<SpriteRenderer>().sortingOrder = -1;
            GetComponent<Collider2D>().enabled = false;
            transform.GetChild(0).gameObject.SetActive(false);
            target.GetComponent<PlayerScript>().GainExperience(100);
            Invoke("EnemyDeath", 1.5f);
        } else
        {
            transform.GetChild(0).gameObject.SetActive(true);
            Invoke("HideBlood", 0.25f);
        }
    }

    void HideBlood()
    {
        transform.GetChild(0).gameObject.SetActive(false);
    }

    void EnemyDeath()
    {
        gameManager.SetZombieCount(-1);
        Destroy(gameObject);
    }

    public int GetHitStrength()
    {
        return hitStrength;
    }
}

Always look for the error message to get more information about what happened. The NullRefException is one of the most common exceptions that can happen, and it means you’re trying to access a variable whose value either hasn’t been set or has been destroyed since (in other words, a value that is null). Part of that error message is called a “stack trace”, it shows the path the code took up until the point where the error happened, sometimes that can provide important information in figuring out why something is happening.

In your case though, the first line of the error already provides useful info: it says the error happened in the EnemyScript.cs, specifically on line 33:

range = Vector2.Distance(transform.position, target.position);

We know what a NullRef is (trying to access a null variable) and in which line the error happened, the next step is pin-pointing where exactly the error (could have) happened. In this case, there’s only one possibility, which is the target variable. The thought process:

  • range is being assigned to, so we’re not trying to access it
  • Vector2.Distance is a static method, no way of getting a NullRef here either
  • transform is a field of the current gameObject, the only way this can be null is if the current gameObject has been destroyed, in which case the Update() would not have been called.
  • target is assigned at Start(), so it’s the only one that could have lost it’s reference since then (for whatever reason). Since you’re assigning it through a GameObject.Find() call, it’s possible it’s not able to find it (in which case you’d get a different NullRefException for trying to call .transform from a null result from GameObject.Find().

You can also use Debug.Log() to try and test some assumptions you have and eliminating some possibilities. For example, after assigning target in the Start() method, you could try adding a line like Debug.Log("Target is null: " + target == null); or the same line in the Update() method, just before the line where the exception happens.

When you’re comfortable with all that, getting into debugging with breakpoints would be a good next step.

Hope this helps!

1 Like