Hi.
I made two Coroutines.
One for wander and one for chase.
I used all kind of code to make wander stops when chasing, but it almost never chases player and wander.
I used yield break, yield return null, stopcoroutine, named it with string, etc…
But it never stops wandering…
I just let them yield break to see if it will make my wandering stops, but it doesn’t!!
Here is my code.
Help me God bless you all.
public Transform sight;
public GameObject Player;
NavMeshAgent navMeshAgent;
NavMeshPath path;
public float timeForNewPath;
Vector3 target;
bool inCoRoutine;
bool chasing;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent> ();
path = new NavMeshPath ();
chasing = false;
navMeshAgent.speed = speedController.speedValue;
}
void Update()
{
// Two CoRoutines with chasing and wandering.
if (!inCoRoutine && !chasing)
{
StartCoroutine ("Wandering");
StopCoroutine ("Chase");
}
if (chasing)
{
StartCoroutine ("Chase");
StopCoroutine ("Wandering");
}
//This is for move animation.
if (navMeshAgent.velocity.magnitude > 1.0f)
{
anim.SetBool ("IsWalking", true);
}
else
{
anim.SetBool ("IsWalking", false);
}
}
Vector3 getNewRandomPosition()
{
float x = Random.Range (-45, -5);
float y = Random.Range (-0.2f, 0.2f);
float z = Random.Range (-33, 25);
Vector3 pos = new Vector3 (x, y, z);
return pos;
}
IEnumerator Wandering()
{
if (!chasing)
{
inCoRoutine = true;
yield return new WaitForSeconds (timeForNewPath);
GetNewPath ();
inCoRoutine = false;
}
if (chasing)
{
yield break;
}
}
IEnumerator Chase()
{
if (chasing)
{
GetNewPath ();
yield return new WaitForSeconds (timeForNewPath);
target = Player.transform.position;
navMeshAgent.SetDestination (target);
}
if (!chasing)
{
yield break;
}
}
void GetNewPath()
{
if (!chasing)
{
target = getNewRandomPosition ();
navMeshAgent.SetDestination (target);
}
else if (chasing)
{
target = Player.transform.position;
navMeshAgent.SetDestination (target);
}
}
void OnTriggerStay()
{
Ray ray = new Ray (sight.position, sight.forward);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 30.0f))
{
sight.LookAt (Player.transform.position);
if (hit.transform.CompareTag ("Player"))
{
chasing = true;
Debug.Log ("Hello");
}
else
{
chasing = false;
Debug.Log ("No");
}
}
}
void OnTriggerExit()
{
chasing = false;
}
}