Hey there. I coding an AI for my game and I get in trouble for using coroutine (and I think is the only way ). The code below is timer function. Code (CSharp): private IEnumerator LookUpTimer() { // Coroutine running true CR_LookUpTimer = true; // Set timer auxDelayToLook = delayToLook; // Record the original rotation Quaternion originalRotation = pivotRightArm.rotation; // execute until timer = 0 while (auxDelayToLook > 0) { // pause yield return null; float rot = 45 * Time.fixedDeltaTime; // rotates 45 * (value of fixed frame rate update) if (pivotRightArm.rotation.z + rot > pivotRightArm.rotation.z) { pivotRightArm.Rotate(Vector3.forward, rot, Space.Self); } // decrement the value of timer (minus value of fixed frame rate update) auxDelayToLook -= Time.fixedDeltaTime; } // Set the original rotation pivotRightArm.rotation = originalRotation; // Walk behaviour is free canWalk = true; // Coroutine running false CR_LookUpTimer = false; // Stop the coroutine yield break; } The code above only executes if the function StartLookUp is called: Code (CSharp): private void StartLookUp() { if (!CR_LookUpTimer) StartCoroutine(LookUpTimer()); } And the coroutine only executes if not running. I have a Switch on FixedUpdate to control the behaviours and the AI don't out from that part: Code (CSharp): case behaviour.idle: // out from IDLE // start PURSUIT if (CanFollow()) StartPursuit(); // out from IDLE // start WALK else if (CanWalk()) StartWalk(); // stay IDLE else { StartLookUp(); } break; (The function CanWalk() returns the bool value of canWalk ) In other words, on start the switch case is behaviour.walk (and he walked nicely). Once in behaviour.idle him can't follow and neither walk (and thats correct). Then StartLook calls LookUpTimer (only if LookUpTimer is not executing). When the LookUpTimer ends the value of canWalk is true and for some reason the switch case behaviour.idle won't detect this. I read the manual about the yield but wasn't great help Please help me I'm gonna crazy with this haha Thanks for reading this far
In essence, your code as posted seems ok. One thing to note, is that the yield break; in your Coroutine is unnecessary at that point- the routine is about to exit, thus ending the Coroutine anyway. I would suggest that your best bet would be to stick breakpoints on canWalk = true;. When you hit that one, add a further breakpoint at else if (CanWalk()). Does the 2nd point get reached as you expect? If not, start moving that breakpoint backwards (in terms of the expected codepath) to find a hit so that you can start stepping through. At this stage, the suspicion would have to be that presumably the CanWalk check is not being reached (as opposed to having a bug in it) and that would mean that either if (CanFollow()) is returning true, case behaviour.idle is not true or the method this is in is simply not being called.