Hi, so I have this script that I got from a tutorial that I got working just fine, I have it set to patrol around a certain place stopping at 6 different waypoints, basically I’m telling my NavMesh AI to walk to the first waypoint, then once it gets there continue to the next, and so on. Now this works perfectly, except it doesn’t loop. I have the waypoints set up like a circle and I want the AI to go back to the first waypoint after reaching the last and loop over and over, and it doesn’t. It gets to the last waypoint and then doesn’t change direction and runs right into the wall and stays there until I restart the game. How do I get my code to go back to the first waypoint after getting to the last of an array of checkpoints??
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using System;
namespace UnityStandardAssets.Characters.ThirdPerson
{
public class basicAI : MonoBehaviour
{
public NavMeshAgent agent;
public ThirdPersonCharacter character;
public enum State
{
PATROL,
CHASE
}
public State state;
private bool alive;
// Variables For Patrolling
public GameObject[] waypoints;
private int waypointInd = 0;
public float patrolSpeed = 0.5f;
// Variables for Chasing
public float chaseSpeed = 1f;
public GameObject target;
// Use this for initialization
void Start()
{
agent = GetComponent<NavMeshAgent>();
character = GetComponent<ThirdPersonCharacter>();
agent.updatePosition = true;
agent.updateRotation = false;
state = basicAI.State.PATROL;
alive = true;
StartCoroutine("FSM");
}
IEnumerator FSM()
{
while (alive)
{
switch (state)
{
case State.PATROL:
Patrol();
break;
case State.CHASE:
Chase();
break;
}
yield return null;
}
}
void Patrol()
{
agent.speed = patrolSpeed;
if (Vector3.Distance (this.transform.position, waypoints[waypointInd].transform.position) >= 2)
{
agent.SetDestination(waypoints[waypointInd].transform.position);
character.Move(agent.desiredVelocity, false, false);
}
else if (Vector3.Distance (this.transform.position, waypoints[waypointInd].transform.position) <= 2)
{
waypointInd += 1;
if (waypointInd > waypoints.Length)
{
waypointInd = 0;
}
}
else
{
character.Move(Vector3.zero, false, false);
}
}
void Chase()
{
agent.speed = chaseSpeed;
agent.SetDestination(target.transform.position);
character.Move(agent.desiredVelocity, false, false);
}
private void OnTriggerEnter(Collider coll)
{
if (coll.tag == "Player")
{
state = basicAI.State.CHASE;
target = coll.gameObject;
}
}
}
}