- Home /
Coroutine does not seem to work
Hello,
I'm not very fond of coroutines yet, but here's basically what I'm trying to do: I want to change the color of a button (one out of four) for 1 second and I use states for that (Button_pressed = color, button_unpressed = no color). I change a bool variable in order to accomplish the state change.
Every round another button adds and I want to change the color of the buttons consecutively --> I need to delay the state changes of the buttons 2,3,4... otherwise the state changes will overlap.
I've tried many things so far and currently I'm stuck here:
Update() //Call GenerateNewButton() if the all the previous buttons have been displayed
GenerateNewButton() //Generate new Random (1-4) for the button that's supposed to change color and call PlayButton()
PlayButton() //Call the recursive function PlayCurrentButton
PlayCurrentButton() //Set Variable for the state change and call PlayCurrentButton again (with the next button) as long as there is a button to display
Here the exact code of the last function:
public void PlayCurrentButton(int Round)
{
if (PublicClass.ButtonList[Round] == 1){
AnimatorDown.SetBool("DownPressed",true);
}
else if (PublicClass.ButtonList[Round] == 2){
AnimatorRight.SetBool("RightPressed",true);
}
else if (PublicClass.ButtonList[Round] == 3){
AnimatorUp.SetBool("UpPressed",true);
}
else if (PublicClass.ButtonList[Round] == 4){
AnimatorLeft.SetBool("LeftPressed",true);
}
StartCoroutine(WaitForAnimation(Round));
if (Round != PublicClass.ButtonList.Count-1) {
PlayCurrentRound(Round+1);
}
}
IEnumerator WaitForAnimation(int Round)
{
yield return new WaitForSeconds(10.0f);
}
The problem is, that the Coroutine does not seem to work, there is no delay and the state changes overlap. I've already read many similar discussions about coroutines but I just can't seem to figure out the problem.
Thanks in advance ~
Answer by whydoidoit · Mar 12, 2014 at 04:09 PM
Your coroutine does nothing. Calling StartCoroutine from inside a normal function just starts that as a parallel track of execution and as it immediately waits and terminates.
If you wanted something to wait you would need to make the whole thing a coroutine or make a coroutine that does something after a period of time.
That latter can be achieved like this:
public IEnumerator DoAfter(float delay, System.Action operation) {
yield return new WaitForSeconds(delay);
operation();
}
And then you might call it in your code like this:
public void PlayCurrentButton(int Round)
{
if (PublicClass.ButtonList[Round] == 1){
AnimatorDown.SetBool("DownPressed",true);
}
else if (PublicClass.ButtonList[Round] == 2){
AnimatorRight.SetBool("RightPressed",true);
}
else if (PublicClass.ButtonList[Round] == 3){
AnimatorUp.SetBool("UpPressed",true);
}
else if (PublicClass.ButtonList[Round] == 4){
AnimatorLeft.SetBool("LeftPressed",true);
}
StartCoroutine(DoAfter(10, ()=>{
if (Round != PublicClass.ButtonList.Count-1) {
PlayCurrentRound(Round+1);
}
}));
}