I am trying to get my script, which is used for my enemy AI, to find my players transform but I keep getting the error:
NullReferenceException: Object reference not set to an instance of an object
AiChasePlayerState.Update (AiAgent agent) (at Assets/AiChasePlayerState.cs:36)
AiStateMachine.Update () (at Assets/AiStateMachine.cs:33)
AiAgent.Update () (at Assets/AiAgent.cs:25)
The following is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AiChasePlayerState : AiState
{
public Transform playerTransform;
float timer = 0.0f;
Animator animator;
public AiStateId GetId()
{
return AiStateId.ChasePlayer;
}
public void Enter(AiAgent agent)
{
if (playerTransform == null)
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
}
}
public void Update(AiAgent agent)
{
timer -= Time.deltaTime;
if (timer < 0.0f)
{
float sqDistance = (playerTransform.position - agent.navMeshAgent.destination).sqrMagnitude;
if (sqDistance > agent.config.maxDistance * agent.config.maxDistance)
{
agent.navMeshAgent.destination = playerTransform.position;
}
timer = agent.config.maxTime;
}
agent.navMeshAgent.destination = playerTransform.position;
animator.SetFloat("Speed", agent.navMeshAgent.velocity.magnitude);
}
public void Exit(AiAgent agent)
{
}
}
I have tagged my player with the tag "Player"
so I don’t know why this is happening. Please help me, thank you.
I tried following the Youtube video:
but I got lost because the guy updated his code without addressing it.