- Home /
How to loop IEnumerator
I'm fairly new to coding so forgive me for being dumb. I need thing code to restart itself when it reaches this --> //Keep restarting IEnumerator forever.)
using System.Collections;
using UnityEngine;
public class Thing_Head_Animator : MonoBehaviour
{
public GameObject Thing_Head_R;
public GameObject Thing_Head_L;
// Use this for initialization
void Start ()
{
StartCoroutine (Thing_Head_Animation ());
}
IEnumerator Thing_Head_Animation()
{
Thing_Head_R.SetActive (true);
yield return new WaitForSeconds (10.0f);
Thing_Head_R.SetActive (false);
Thing_Head_L.SetActive (true);
yield return new WaitForSeconds (10.0f);
Thing_Head_L.SetActive (false);
//Keep restarting IEnumerator forever.
}
}
I'm just wondering you bother setting Thing_Head_L .SetActive() to false because you end up setting it to true in the next frame. No user would be able to see the switch.
Answer by Prastiwar · Aug 17, 2018 at 04:14 PM
Just put whole scope into while loop
IEnumerator Thing_Head_Animation()
{
while(true) // you can put there some other condition
{
Thing_Head_R.SetActive (true);
yield return new WaitForSeconds (10.0f);
Thing_Head_R.SetActive (false);
Thing_Head_L.SetActive (true);
yield return new WaitForSeconds (10.0f);
Thing_Head_L.SetActive (false);
}
}
I would say you $$anonymous$$UST put some conditions there, because everytime I use while(true)
my computer screams "No! Please, stop this! I could die here right now!".
No, there is no "must" as long as you ensure you have a yield return inside the loop. Of course a yield return that is actually reached. There is no problem having a while (true)
loop. For "normal" code you just have to ensure you actually leave the loop somehow. For coroutines you just have to ensure you have a yield in between.
Your answer
Follow this Question
Related Questions
Crash on loop using Lerp. 1 Answer
Problems with do-while loops and IEnumerator 1 Answer
How can i repeat or loop through terrain? 1 Answer
particles emitter loop 1 Answer
How do i repeat the animation? 3 Answers