I am getting a null reference exception and i am not sure why

I am getting a null reference exception and i am not sure why.
Here is my code.
Please help.

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

public class Shooter : MonoBehaviour {

    [SerializeField] GameObject projectile, gun;
    AttackerSpawner myLaneSpawner;

    private void Start()
    {
        SetLaneSpawner();
    }

    private void Update()
    {
        if(IsAttackerInLane())
        {
            Debug.Log("shoot pew pew");
            // TODO change animation state to shooting
        }
        else
        {
            Debug.Log("sit and wait");
            // TODO change animation state to idle
        }
    }

    private void SetLaneSpawner()
    {
        AttackerSpawner[] spawners = FindObjectsOfType<AttackerSpawner>();

        foreach (AttackerSpawner spawner in spawners)
        {
            bool IsCloseEnough = 
                (Mathf.Abs(spawner.transform.position.y - transform.position.y) 
                <= Mathf.Epsilon);
            if (IsCloseEnough)
            {
                myLaneSpawner = spawner;
            }
        }
    }

    private bool IsAttackerInLane()
    {
        if (myLaneSpawner.transform.childCount <= 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public void Fire()
    {
        Instantiate(projectile, gun.transform.position, transform.rotation);
    }

}

Hi,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.

There is a variable in your IsAttackerInLane method: myLaneSpawner.

Check where a lane gets assigned to this variable. The y-coordinates of both the defender and the spawner must be equal. Otherwise, the condition gets evaluated to false, and nothing gets assigned to myLaneSpawner. If the variable is empty, it is null, thus the NullReferenceException.

Did this help?


See also:

I don’t really understand. I am sorry but could you explain some more please?

Have you already rewatched the video at least one more time? Make sure that the position of the spawner parent is set to (0, 0, 0). And its children (the spawner game objects) must have rounded y-position values. If in doubt, rewatch the video and compare your values with Rick’s.

omg thanks it worked. thank you so much

You’re welcome. :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.