So I've ran into something weird, when using a co-routine in Unity to simulate a NPC (walks towards a target, idles for x seconds, walks to a target --repeat--).
I've found that starting the co-routine with a variable that holds the IEnumerator will not run twice, while starting the co routine with the method passed in directly runs as expected, repeatable.
Why does this work this way? Whats happening 'under the hood'? I cant wrap my head around why this is, and it bugs me.
Below my IEnumerator method that simulates idle time.
private IEnumerator sitIdle()
{
var timeToWait = GetIdleTime();
_isIdle = true;
yield return new WaitForSeconds(timeToWait);
_isIdle = false;
}
If this gets called a second time per Scenario #1 (below), it runs as expected when called multiple times. It just repeats the process over and over.
If however, if it gets called per Scenario #2 (below) as a variable, it will kick off once, but refuse to enter a second time and just plain 'skip' it in code.
void LateUpdate()
{
_idleRoutine = sitIdle; //this is not actually in the late update, just moved here for reference.
if (_agent.hasPath)
{
if (isTouchingTarget())
{
StartCoroutine(sitIdle2()); //Scenario #1
StartCoroutine(_idleRoutine); //Scenario #2
_currentTarget = null;
_agent.ResetPath();
}
}
Tl;dr: StartCoroutine(variable to IEnumerator) is not repeatable, while StartCoroutine(IEnumerator()) works fine, why cant I pass the IEnumerator as a variable?
_idleRoutine = sitIdle();? - RuzihmStartCoroutineyour method, or something Unity provides? My guess would be that if it's taking an instance ofIEnumeratorthat it's iterating through theIEnumeratorby callingMoveNextin awhileloop. When you passStartCoroutinethe result ofsitIdleyou're passing a new instance ofIEnumerator. However, if you put the result ofsitIdlein a variable then once you callStartCoroutineonce, you've already iterated past the end of theIEnumerator. So the next time you pass it toStartCoroutine,MoveNextjust returnsfalse. - Joshua RobinsonStartCoroutine- Ruzihm