So I watched a tutorial on how to make an A.I walk, chase and attack. Everything was working fine until I got to the chase scene which resulted in the warning of “NullReferenceException: Object reference not set to an instance of an Object”, so what I want this script to do, is when the player reaches the sightRange value I’ve inputted, it’ll run the “Chase” method and proceed to go after the player. But whenever I test my game and go up to my A.I character, that object reference error bit started popping up. For my player controller I’m using Unity’s third person starter asset, for the layer which is what the code is using for reference, I’ve just added in the Player layer to the PlayerArmature object as that’s the only object with changing positions, I didn’t change the rest of the children and just it’s parent overall.
Note: Added in debug logs since before it wasn’t doing anything at all, after tweaking some stuff within the nav mesh agent and nav mesh surface, the nullreference bit started popping up.
My referenced code:
GameObject player;
NavMeshAgent agent;
[SerializeField] LayerMask groundLayer, playerLayer;
//Patrol
Vector3 destPoint;
bool walkpointSet;
[SerializeField] float range;
Animator animator;
//State change
[SerializeField] float sightRange, attackRange;
bool playerInSight, playerInAttackRange;
void Start()
{
agent = GetComponent();
player = GameObject.Find(“Player”);
}
void Update()
{
playerInSight = Physics.CheckSphere(transform.position, sightRange, playerLayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, playerLayer);
if (!playerInSight && !playerInAttackRange) { Patrol(); }
if (playerInSight && !playerInAttackRange) { Chase(); }
if (playerInSight && playerInAttackRange) { Attack(); }
}
void Patrol()
{
if (!walkpointSet) SearchForDestination();
if(walkpointSet) agent.SetDestination(destPoint);
if (Vector3.Distance(transform.position, destPoint) < 10) walkpointSet = false;
}
void Chase()
{
agent.SetDestination(player.transform.position);
Debug.Log(“Chase method executed”);
}
void Attack()
{
if (!animator.GetCurrentAnimatorStateInfo(0).IsName(“AttackingSigbin”))
{
animator.SetTrigger(“Attack”);
agent.SetDestination(destPoint);
Debug.Log(“Attack method executed”);
}
}
void SearchForDestination()
{
float z = Random.Range(-range, range);
float x = Random.Range(-range, range);
destPoint = new Vector3(transform.position.x + x, transform.position.y, transform.position.z + z);
if(Physics.Raycast(destPoint, Vector3.down, groundLayer))
{
walkpointSet = true;
}
}