- Home /
Coroutine not working as expected
I want to change state of a Gameobject using script. While going from one state to another, I want a little delay to be introduced.
The script as of now is
public enum TextState {
Start,
ChooseAction
}
public TextState currentState;
void Start () {
currentState = TextState.Start;
}
void Update () {
if (currentState == TextState.Start)
doStart();
if (currentState == TextState.ChooseAction)
doChooseAction();
}
}
void doStart(){
var t = GameObject.Find ("TextBox").GetComponent<TextAnimation>() ;
t.showText ("X attacked you!!");
StartCoroutine(doWait());
currentState = TextState.ChooseAction;
}
void doChooseAction(){
Debug.Log("On ChooseAction");
}
IEnumerator doWait(){
yield return new WaitForSecondsRealtime(100);
Debug.Log ("waited for 100");
}
showNext is a function defined in another script used to animate text using coroutine, with letters appearing after short delay.
As of now the Debug statement in doWait() isn't being run, and state immediately changes to chooseAction
What I know till now is that yield in my coroutine gives control back to rest of code and the subsequent lines aren't running. If anyone could help me with this and point out how to implement the coroutine it'd be a great help.
Answer by MacDx · Oct 18, 2017 at 06:33 PM
You just need to move this line:
currentState = TextState.ChoosenAction;
And put it inside the coroutine.
So it would look like this:
IEnumerator doWait()
{
yield return new WaitForSecondsRealtime(100);
currentState = TextState.ChooseAction;
Debug.Log("waited for 100");
}
Corotuines will yield but only for stuff that is inside them, not outside. Also try reducing the wait time to like 3 seconds, just for testing. Waiting more than a minute every time you want to test the code, seems like a waste of time :P
Working correctly now. The time was big because the change was instantaneous so just put a big number. $$anonymous$$any thanks
$$anonymous$$oving this line:
currentState = TextState.ChoosenAction;
after the yield is not a good idea as Update will continue to call "doStart" every frame and start a new coroutine every frame.
I did think of it and have added a bool which is true whenever a doSomething() is entered and false as soon as doWait() is finished and if statment in update checks if the bool is false. This way update only changes states when no other state is running. I hope this is a correct approach.