- Home /
Coroutines and if statements
I have this code here:
void speed()
{
//Debug.Log (LeftRightMovement.speed);
if(GUICounters.speed == 1)
{
//Debug.Log (LeftRightMovement.speed);
LeftRightMovement.speed = 60;
StartCoroutine(timer ());
//Debug.Log (LeftRightMovement.speed);
}
}
IEnumerator timer()
{
Debug.Log (LeftRightMovement.speed);
yield return new WaitForSeconds(5);
LeftRightMovement.speed = 30;
}
My players speed is currently 30, when LeftRightMovement.score reaches a certain point I would like to increase the speed to 60 for 5 seconds using the coroutine and then set the speed back to 30 but as it is the speed is constantly at 60.
I also tried wrapping it in a boolean as i think its because it runs every frame and my score is always at 1. This is what i tried:
void speed()
{
if(ranOnce = false)
{
//Debug.Log (LeftRightMovement.speed);
if(GUICounters.speed == 1)
{
//Debug.Log (LeftRightMovement.speed);
LeftRightMovement.speed = 60;
StartCoroutine(timer ());
//Debug.Log (LeftRightMovement.speed);
}
ranOnce = true;
}
}
But i had no luck with that either, nothing comes out form the Debug.Log() then.
If anyone could point me in the right direction, that'd be great
The bool method should work, as long a runOnce starts off as false.
Answer by Bunny83 · Aug 16, 2014 at 11:49 PM
Your boolean method would work if your condition would look like this:
if(ranOnce == false)
Instead of
if(ranOnce = false)
= assignment operator
== equals operator
PS: since we don't know where and how often you call your "speed" method and on which object, there could be countless other things which might break your logic. For example if you destroy the GameObject that runs this coroutine, the coroutine will die silently.
You also should be more clear about what exactly doesn't work
Argh I never even noticed that, ill try it out first thing tomorrow. Thanks for the input bunny
Your answer
Follow this Question
Related Questions
Making a level up button., 2 Answers
how to start coroutines in the update method? 3 Answers
How can I use a yeild during an udate? 1 Answer