Problem: Null Reference Exception at Shooter Script

I’m having some problems right now. I was writing the script for the shooter, and despite that I got everything right and I didn’t make an error in the script itself, I keep getting this error message in the console.


The worst part is that because of the error the cactus refuses to change it’s animation. Can somebody help me?

What is line 47 of the shooter.cs doing. Looks like you are calling a reference to an object that is not. Maybe it wasn’t assigned in the inspector

Every spawner’s assigned as an AttackerSpawner in the Inspector. I’m now not so sure what I missed. Is there something in my code that needs to be fixed? Or something in the inspector that needs to be done?

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

public class Shooter : MonoBehaviour
{
    [SerializeField] GameObject projectile;
    [SerializeField] GameObject shootPos;
    AttackerSpawner myLaneSpawner;
    Animator animator;

    public void Start()
    {
        SetLaneSpawner();
        animator = GetComponent<Animator>();
    }

    public void Update()
    {
        if (IsAttackerInLane())
        {
            animator.SetBool("IsAttacking", true);

        } else
        {
            animator.SetBool("IsAttacking", 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, shootPos.transform.position, Quaternion.identity);
    }
}

I suspect that Unity is not finding the animator on the cactus. Check that and maybe Devi’s the update method

The animator is already on the cactus and I’ve revised the code and I didn’t find anything in the Update method, and error is still on line 47. Did I miss something? Is there something I have to do in Unity 2019.2 I need to fix?

Does the y-position of your defender match the y-position one spawner? Check by logging the position values into your console.

I fixed it, and now it works! Thank you so much!!!

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

Privacy & Terms