Enemy AI in C# please!!!

I have a C# script called “EnemyAI”. This is the entire script:

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour 
{
	public Transform checkPoint1;
	public Transform checkPoint2;
	public Transform checkPoint3;
	public Transform checkPoint4;

	public NavMeshAgent nav;

	void Awake ()
	{
		nav = GetComponent<NavMeshAgent> ();
	}

	void Start ()
	{
		nav.SetDestination (checkPoint1.position);
	}

	void Update ()
	{	
		if (nav.destination == checkPoint1.position) 
		{
			nav.SetDestination(checkPoint2.position);
		}
		
		if (nav.destination == checkPoint2.position) 
		{
			nav.SetDestination (checkPoint3.position);
		}
		
		if (nav.destination == checkPoint3.position) 
		{
			nav.SetDestination(checkPoint4.position);
		}
		
		if (nav.destination == checkPoint4.position) 
		{
			nav.SetDestination(checkPoint1.position);
		}
	}

}

The problem is that when I run the game in the editor, the object sits still. Even though it has a “NavMeshAgent” component on it, the script doesn’t work. Any ideas? Thanks!

There are three things wrong with your approach:

  • You’re resetting the destination every frame. It normally takes a short time for the agent to determine a route before it starts moving. Because you’re giving it a new route to calculate every frame (even if it is to the same destination) it never gets a chance.

  • You’re comparing whether the current destination is equal to cp1 and, if it is, set the current destination to cp2. Then set it to cp3, then cp4, then back to cp1. So the destination at the end of every iteration of the Update() loop will always be cp1 (which is where you started). I suspect you meant to test whether the position of the character is equal to cp1, cp2 etc.

  • Finally, you shouldn’t ever test whether two positions are equal.Instead, check whether the distance between them is equal to some acceptably small tolerance. This will allow for floating-point inaccuracies.