Enumerator in for loop acting strangely
Hiya, i'm trying to make it so that a random orb gets selected, after which the ID of the orb gets stored in an array untill the specified number of orbs get stored. However when i use this snippet, here's what happens:
All selected orbs light up and the same time instead of in a sequence
all lit up orbs stay on as specified by the first yield waitforseconds
too many orbs get selected (diffMult = 2, Difficulty =0, seQuenceSize =4)
This leads me to believe that the for loop runs all iterations of the enumerator alongside eachother... Any ideas on how i can get it to run each after the previous one has finished?
public void StartSequence()
{
//how big a sequence is
diffMult *= difficulty;
sequenceSize += diffMult;
//sets the lengths of int[] randomSequence
randomSequence = new int[sequenceSize];
//chooses object i, then fills randSequence in for which item was chosen, then sets chosen object.chosen to true for a time, then sets it back to false.
for (int i = 0; i < sequenceSize; i++)
{
var randDot = (int)Random.Range(0, 5);
randomSequence[i] = randDot;
StartCoroutine(Sequence(randDot));
}
}
IEnumerator Sequence(int randDot)
{
dots[randDot].GetComponent<ExampleDotScript>().chosen = true;
yield return new WaitForSeconds(1.5f);
dots[randDot].GetComponent<ExampleDotScript>().chosen = false;
yield return new WaitForSeconds(1.0f);
Debug.Log("dot chosen");
}
Answer by vintar · Jan 12, 2016 at 08:42 PM
Yes, you are correct in assuming that they are running alongside each other, you could try something like this (not tested) :
public IEnumerator StartSequence()
{
//how big a sequence is
diffMult *= difficulty;
sequenceSize += diffMult;
//sets the lengths of int[] randomSequence
randomSequence = new int[sequenceSize];
int count = sequenceSize;
while(count > 0)
{
yield return StartCoroutine(Sequence());
count--;
}
}
IEnumerator Sequence(int randDot)
{
var randDot = (int)Random.Range(0, 5);
randomSequence[i] = randDot;
dots[randDot].GetComponent<ExampleDotScript>().chosen = true;
yield return new WaitForSeconds(1.5f);
dots[randDot].GetComponent<ExampleDotScript>().chosen = false;
yield return new WaitForSeconds(1.0f);
Debug.Log("dot chosen");
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612055713im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Array Index is out of range 1 Answer
Avoid looping in shader 0 Answers
Instantiating in a for loop is causing an infinite loop? 2 Answers
Yield return statement ends loop execution 0 Answers
Loops when generating random string 1 Answer