Hi, I’m trying to make a simple finite state machine for my ai and I’m having a problem to make idle state. What I want for my idle state is if my state machine is in idle, it will wait for random range from 3-5 seconds then go to another state, but the wait can be interrupt when the something trigger. I have no Idea how to make script that wait for certain number of seconds. So here is what I have so far for my state machine.
using UnityEngine;
using System.Collections;
public class AI : MonoBehaviour
{
public enum State
{
Idle,
Wander,
Moving,
Follow,
Attack
}
SphereCollider sphere;
NavMeshAgent agent;
float walkRadius;
State _state;
void Awake()
{
sphere = GetComponent<SphereCollider> ();
agent = GetComponent<NavMeshAgent> ();
walkRadius = sphere.radius;
_state = State.Idle;
StartCoroutine ("FSM");
}
IEnumerator FSM()
{
while(true)
{
switch(_state)
{
case State.Idle:
Idle();
break;
case State.Wander:
Wander();
break;
case State.Moving:
Moving();
break;
case State.Follow:
break;
case State.Attack:
break;
}
yield return null;
}
}
void Idle()
{
Debug.Log ("Idle");
_state = State.Wander;
}
void Wander()
{
Vector3 randomDirection = Random.insideUnitSphere * walkRadius;
randomDirection += transform.position;
NavMeshHit hit;
NavMesh.SamplePosition(randomDirection, out hit, walkRadius, 1);
agent.SetDestination(hit.position);
_state = State.Moving;
Debug.Log ("Moving");
}
void Moving()
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
Debug.Log("Done moving, going to idle");
_state = State.Idle;
}
}
}