NullReferenceException in IsInChaseRange() 3rd Person Combat

I’m geting a NullReferenceException that I can’t seem to nail down (screenshot below).
I’m thinking it’s really complaining about deltaTime as it’s a local float variable (which is never set) vs. Time.deltaTime but it’s how the instructor wrote it and he didn’t get an exception. I’m trying to figure out where I went wrong.

The code in IsInChaseRange() matches.

    protected bool IsInChaseRange()
    {
        float playerDistanceSqr = (stateMachine.Player.transform.position - stateMachine.transform.position).sqrMagnitude;
        
        return playerDistanceSqr <= stateMachine.PlayerChasingRange * stateMachine.PlayerChasingRange;
    }

Where IsInChaseRange()) is called.

if (IsInChaseRange())
        {
            Debug.Log("In Range");
            //Transition to chasing state
            return;
            
        }

It’s in the IsInChaseRange method. If I comment out the If(IsInChaseRange()) call, I do not get the error message. Using Debug.Log() on that method I found that I can Debug.Log() stateMachine.transform.position but not stateMachine.Player.transform.position. So why is the Player’s transform position coming back as null?

OK, I found it. In EnemyStateMachine, I had this line:

GameObject.FindGameObjectWithTag("Player");

It should read:

Player = GameObject.FindGameObjectWithTag("Player");

Good job finding that. I just saw the thread and was about to suggest checking to make sure you’ve correctly tagged the player and located the player in Awake() or Start(). It’s pretty much the only thing in that method that would generate a null reference error.

1 Like

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

Privacy & Terms