- Home /
Question by
AmazingDeveloper2 · Jan 03, 2015 at 12:50 PM ·
coroutine
Two coroutinew doesn't works together
In my game I have two coroutines, but when I start simulation, Unity freezes.
Edited. Here is the full code
public GameObject[] timeImages;
public GameObject[] time00X0;
public GameObject[] time000X;
bool isTimeEnabled;
int timeValue00X0;
int timeValue000X;
void Start ()
{
timeValue00X0 = Random.Range (4, 5);
timeValue000X = 0;
time00X0 [timeValue00X0].SetActive (true);
time000X [timeValue000X].SetActive (true);
StartCoroutine ("Time000X");
StartCoroutine ("Time00X0");
}
IEnumerator Time000X()
{
while (true)
{
isTimeEnabled = !isTimeEnabled;
foreach(GameObject i in timeImages)
i.SetActive (isTimeEnabled);
time000X[timeValue000X].SetActive(true);
yield return new WaitForSeconds(0.5f);
time000X[timeValue000X++].SetActive(false);
if(timeValue000X == 10)
timeValue000X = 0;
}
}
IEnumerator Time00X0()
{
while(true)
{
if(timeValue000X == 0)
{
time00X0[timeValue00X0].SetActive(true);
yield return new WaitForSeconds(0.5f);
time00X0[timeValue00X0++].SetActive(false);
}
if(timeValue00X0 == 3)
timeValue00X0 = 0;
}
}
Can't understand, what's wrong
Comment
2 basic coroutines work fine for me, what code is in your IEnumerator methods, does the following work for you:
void Start(){
StartCoroutine("Time000X");
StartCoroutine("Time00X0");
Debug.Log("here");
}
IEnumerator Time000X(){
yield return new WaitForSeconds(3);
Debug.Log(Time.time);
}
IEnumerator Time00X0(){
yield return new WaitForSeconds(2);
Debug.Log(Time.time);
}
Best Answer
Answer by Scribe · Jan 03, 2015 at 07:16 PM
your problem is that if timeValue000X doesn't equal 0, then you will never reach a yield statement in IEnumerator Time00X0 and therefore your frame will never progress and timeValue000X will never change and so it goes on forever. You should add yield return null; to the end of the second IEnumerator so it will progress without doing anything even if timeValue000X is not 0
Your answer