Null exception issue

Shooter script throw Null reference exception despite I filled both fields exposed in inspector

public class shooter : MonoBehaviour
{
[SerializeField] GameObject projectile;
[SerializeField] GameObject gun;
AttackerSpawner myLaneSpawner;
Animator animator;

// Start is called before the first frame update

private void Start()
{
    setLaneSpawner();
    animator = GetComponent<Animator>();
}

private void Update()
{
    if (IsAttackerInLane())
    {
        animator.SetBool("IsAttacker", true);
    }

    else
    {
        animator.SetBool("IsAttacker", false);
    }
}

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, Quaternion.identity);

}

}

The fields you filled in the inspector are not the ones causing the issue though…

The error states that the problem is within the IsAttackenInLane() method, which in turn needs the “myLaneSpawner” field, which is null. You initialize “myLaneSpawner” in the setLaneSpawner() method. Now, there are 2 possiblities here which could cause this null exception:

  1. FindObjectsOfType fails because you don’t have any attack spawners in the scene, or
  2. The isCloseEnough check evaluates to false and “myLaneSpawner = spawner” never executes

I have attack spawners in the scene and they spawn perfectly there is no issue in spawners.My defender just not shoot

Hi Daniyal,

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.

Crystal clear Nina.

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

Privacy & Terms