- Home /
Question by
hopper · Aug 10, 2014 at 05:40 AM ·
c#navmeshnavmeshagent
How to make enemy AI with NavMesh
I have written a script that is supposed to make an enemy go back and forth between control points but it doesn't work. Any ideas?
Heres the script:
using UnityEngine;
using System.Collections;
public class NavTest : MonoBehaviour
{
public Transform target1;
public Transform target2;
NavMeshAgent agent;
void Start ()
{
agent = GetComponent<NavMeshAgent> ();
}
void LateUpdate ()
{
StartCoroutine ("Patrol1");
StartCoroutine ("Patrol2");
}
IEnumerator Patrol1 ()
{
agent.SetDestination (target1.position);
yield return new WaitForSeconds (0.5f);
}
IEnumerator Patrol2 ()
{
agent.SetDestination (target2.position);
yield return new WaitForSeconds(0.5f);
}
}
It goes to the first point but doesn't go to the second point.
Comment
Answer by tanoshimi · Aug 10, 2014 at 06:48 AM
In every LateUpdate() (i.e. in every frame), you're resetting the agent's target, first to target1 and then immediately to target2. You only need to SetDestination once, and then set the next waypoint only when the agent reaches the current destination.
Perhaps combining it like this would work?
void LateUpdate ()
{
StartCoroutine ("Patrol");
}
IEnumerator Patrol ()
{
agent.SetDestination (target1.position);
yield return new WaitForSeconds (0.5f);
agent.SetDestination (target2.position);
yield return new WaitForSeconds(0.5f);
}
Answer by Ninja_Bunny · Mar 31, 2021 at 12:04 PM
Vector3 pos;
void LateUpdate () { agent.SetDestination(pos); }
IEnumerator Patrol ()
{
pos = target1.position;
yield return new WaitForSeconds (0.5f);
pos= target2.position;
yield return new WaitForSeconds(0.5f);
}