So this is my pseudo code (dont want to attach whole thing because its a lot)
foreach (GameObject o in Objects) {
bool condition = Some Condition Here;
Debug.Log(condition); // This returns correctly 2 diferent values
if (condition) {
StartCoroutine(RotateCube(o));
}
}
IEnumerator RotateCube(GameObject o)
{
Debug.Log(o); // this returns only 1 object, the wrong one Objects[0] instead of Objects[1]
//do stuff here
}
So the “condition” is setup this way, that it will return true to ONLY 1 object. And it does that. And thats what I want, just 1 coroutine that rotates my object.
But when trying to debug whats going on inside coroutine, it looks like its picking wrong object “o”. Only the first one in GameObject Objects.
So besicaly if I Debug.Log(o) outside of coroutine, it returns 2 values (1 true, 1 false). And its corrent, I have only 2 testing GameObject Objects.
But when I Debug.Log(o) inside coroutine, it always returns Objects[0]
Ok you are right. I always avoided that, as I thought its too scary. But actually VS debugger helped me found an issue. So inside Coroutine I have something like this:
IEnumerator RotateCube(cube)
{
if (!isRotating)
{
isRotating = true;
// Do stuff here
// Now Im done
isRotating = false;
}
}
when I keep isRotating always to false, it works great.
It looks that foreach already did the check for the next cube, when the coroutine didnt finish yet. That completely make sense!
But now Im thinking that this value isRotating should have never been set to true, because the condition evaluates properly. And in the debugger it looks like coroutine starts even though the condition is false. So Im back to the problem again…
I am not sure if this is the case here, but foreach will reuse o when storing the result of the next iteration. When using delegates this will lead to all references to o will point at the last value contained by o in the loop.
What you can do is to create a local variable “oLocal” assign it the value of o, and pass oLocal to the coroutine.
foreach (GameObject o in Objects)
{
GameObject oLocal = o;
if (Condition)
StartCoroutine(RotateCube(oLocal));
}