- Home /
Why isn't this IEnumerator getting called?
For some reason the code below isn't printing anything. I am not trying to start a coroutine, I only want to call it once and have it resume execution to where it left off the next time it is called.
void Start()
{
Debug.Log("Start");
Test4A();
Test4A();
}
IEnumerator Test4A()
{
UnityEngine.Debug.Log("Hello");
if (true)
{
UnityEngine.Debug.Log("Stop");
yield return null;
}
UnityEngine.Debug.Log("4");
}
Coroutines are a Unity construct that utilizes he IEnumerator C# syntax. You can't just call it then call it again to resume execution. Both calls here should print "Hello" then "Stop" then return from the function, never to return. You need to store the returned iterator and call 'next' on it.
Answer by maccabbe · Apr 06, 2015 at 03:56 AM
"When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator"
https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
This means you have used a shorthand to define a class with a method which is used to iterate through an IEnumerable list, like you would in a foreach loop. While Test4A returns an IEnumerator, the method is used only when you attempt to get the next element. To do this use IEnumerator.MoveNext(), normally you would do something like
IEnumerator temp=Test4A();
while(temp!=null){
temp=temp.MoveNext();
}
but since you only want to call the method once you can just do
Test4A().MoveNext();
Thanks that worked. I didn't know you had to use "$$anonymous$$oveNext" for an IEnumerator method to do anything though.
Your answer
Follow this Question
Related Questions
Make a laser flickering. 1 Answer
Yield Wait for Seconds (A little help here) 2 Answers
Multiple Cars not working 1 Answer
c# Using an IEnumerator yield WaitForSeconds to temporarily pause a While loop 3 Answers
Distribute terrain in zones 3 Answers