I want to toggle component each second.
But my code enable and disable it offer than one time per second.
Can’t understand, why?
void Update () {
StartCoroutine ("TimeCycle");
}
IEnumerator TimeCycle()
{
if (isTimeEnabled) {
timeImages [0].SetActive (false);
isTimeEnabled = false;
}
else
{
timeImages [0].SetActive (true);
isTimeEnabled = true;
}
yield return new WaitForSeconds (1);
}
You need to rethink your logic a little. Right now, you enter a frame and start the TimeCycle coroutine. That’s all fine…but on the next frame you start another, and the frame after that, and the frame after that, and so on Each one unaware of the other. This is something you would like to call once , so you should be invoking TimeCycle in Start().
The best option is making a loop inside your coroutine.
IEnumerator TimeCycle()
{
while(true){
if (isTimeEnabled) {
timeImages [0].SetActive (false);
isTimeEnabled = false;
}
else
{
timeImages [0].SetActive (true);
isTimeEnabled = true;
}
yield return new WaitForSeconds (1);
}
}
AND don’t forget to invoke this method once. Multiple calls to start this coroutine would still yield same results.
While not exactly an ideal option, it helps when needed.
Keep in mind that you may want to use a boolean variable instead of simple true for “while(true)”.
Kiwasi
December 18, 2014, 3:17am
4
What’s wrong with
IEnumerator TimeCycle() {
while (true){
isTimeEnabled = !isTimerEnabled;
timeImages [0].SetActive (isTimerEnabled);
yield return new WaitForSeconds (1);
}
}
Edit: Just reread your question. The key fix is actually to use Start instead of Update.