- Home /
C# wait X-Seconds in Code before continue in Code?
actually i'm coding a Traffic-light-System. and now i stuck at the point of changing from red to green. How can i wait in the code before it continues, but dont stop the whole Game.
actually i have this, but this stops the whole game
trafficLight.ChangeStatus(Status.Yellow);
System.Threading.Thread.Sleep(2000);
trafficLight.ChangeStatus(Status.Green);
i need to light up the yellow light for about 2 seconds, then it should turn on the Green light, how to do this?
Answer by robertbu · Feb 24, 2013 at 10:00 PM
Quick example in C#:
public class TrafficLight : MonoBehaviour {
void Start () {
StartCoroutine (GreenYellowRed ());
}
IEnumerator GreenYellowRed()
{
while (true) {
Debug.Log ("Green");
yield return new WaitForSeconds(3.0f);
Debug.Log ("Yellow");
yield return new WaitForSeconds(1.0f);
Debug.Log ("Red");
yield return new WaitForSeconds(3.0f);
}
}
}
worked perfectly. just added a bool flag outside the while and set it to false after all changes are done so that the while stops, otherwhise the changes will be repeated
sorry i'm kind new on this, how can i wait secons in the awake function. Corutines can not be loaded from Awake. I need to wait in the Awake :C
You can't make Awake() a coroutine, but you can start a coroutine from Awake(). For example, if you replace Start() in the above with with Awake() it would work.
you are right i can call it, but this dont stops the code excution the courutine make a paralel process D:, how can i wait X seconds (i need to stop the code excecution)
This needs to be opened as a new question. You need to explain exactly what you are trying to do.
Answer by _Grocfex0000 · Oct 20, 2014 at 11:01 AM
im pretty useless scripter but i needed the same thing and so i did it with calculateing stuff and it does not need some kind of really complicated stuff i think this may help you:
public int one;
public int two = 50;
if (one <= two){
one = one -1;
if (one == 40){
dosomethingfirst
} if (one == 30){
dosomethingsecond
}
}
if (one == 0){
one = two; }
}
Answer by kpetkov · Aug 01, 2018 at 10:50 AM
So far so good. What if I need to wait for some period of time from a class that have to be instantiated and not inheriting from MonoBehaviour ? How can I do that ? Thread sleep is not acceptable, also I don't have acces to coroutines. And by the way I also want to be able to wait in the Utility class where every method is static and have to be accessed from anywhere.
Your answer
Follow this Question
Related Questions
WaitForSeconds Problem [C#] 4 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can a Property show one set of values while the Member variables show another? 1 Answer