- Home /
Getting For Loops to work in a Coroutine
Hello,
I have created a function that has two for loops inside for altering a terrain. The function itself works fine but it makes the game hang while it is processing. To fix this I have changed the function to be a co-routine with a yield in the for loop so it returns to function update after each pass.
After several Debug messages placed about the code I have determined that the co-routine is being called by StartCoroutine() but the for loop isn't. Anyone know why that would be?
Here is a stripped down version of the code.
void Update ()
{
if (generate)
StartCoroutine(GenerateLandmass ());
Debug.Log("Setting Seed");
generate = false;
}
if (newTerrainInfo)
{
Terrain.activeTerrain.terrainData.SetHeights(0,0,heightMap);
newTerrainInfo = false;
}
}
IEnumerator GenerateLandmass ()
{
//this shows in the console
Debug.Log("Started world gen co-routine");
for (int y = 0; y < worldSize; y++)
{
//this doesn't show
Debug.Log("row");
for (int x = 0; x < worldSize; x++)
{
DoStuff();
yield return 0;
}
}
newTerrainInfo = true;
}
@Cunnah, there's something strange in your code. The test in line 4 doesn't have its open bracket (this lets the message in line 8 to be always displayed, regardless of the previous instruction). However, I don't understand how it can be compiled, with the closed bracket at line 11. Is there a copy&paste mismatch, maybe?
How did you know that the for loop is not being called? I assumed that you are reading "row" once in your console.. Is it the case?
No the row line never appears, only the first Debug message. I concluded that the for loop never goes through even one iteration. Also the code is copied from a much larger section so it might be a little butchered (The current code is not exactly elegant at the moment).
I should add the program doesn't hang it calls the co-routine and then does nothing after that.
EDIT
@Jamora you might have a point, I originally called my function (DoStuff()) via another... I think worldsize = 0; and is never set in which case my code is working perfectly and I am an idiot.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Terminal-like GUI, wait for input 1 Answer
How can I create variables for each materials to show in inspector (Using Editor) ? 0 Answers
Coroutine without MonoBehaviour 6 Answers