- Home /
Why does this immediately freeze the simulation?
This is my first time using this site. I apologize in advance.
I have tried to write this with for loops as well. In all cases I am able to comment either 1 of the loops successfuly; each individual loop works.
void Start()
{
terrainGuideMesh = GameObject.FindWithTag("TerrainGuide").GetComponent<MeshFilter>().mesh;
terrainGuideBounds = terrainGuideMesh.bounds;
xTileExt=Mathf.RoundToInt(terrainGuideBounds.extents.x/0.1f);
zTileExt=Mathf.RoundToInt(terrainGuideBounds.extents.z/0.1f);
xTileCount=xTileExt*2;
zTileCount=zTileExt*2;
elevTable= new int[xTileCount,zTileCount];
j=0;
while(j<xTileCount)
{
k=0;
while(k<zTileCount)
{
elevTable[j,k]=1;
print((j+1)+" at ("+j+","+k+")");
k++;
}
j++;
}
}
Answer by iwaldrop · Jan 16, 2013 at 06:59 PM
If you're doing this in C# then you shouldn't use a while loop outside of a Coroutine. Try:
void Start()
{
StartCoroutine(BuildTerrain());
}
IEnumerator BuildTerrain()
{
terrainGuideMesh = GameObject.FindWithTag("TerrainGuide").GetComponent<MeshFilter>().mesh;
terrainGuideBounds = terrainGuideMesh.bounds;
xTileExt=Mathf.RoundToInt(terrainGuideBounds.extents.x/0.1f);
zTileExt=Mathf.RoundToInt(terrainGuideBounds.extents.z/0.1f);
xTileCount=xTileExt*2;
zTileCount=zTileExt*2;
elevTable= new int[xTileCount,zTileCount];
j=0;
while(j<xTileCount)
{
k=0;
while(k<zTileCount)
{
elevTable[j,k]=1;
print((j+1)+" at ("+j+","+k+")");
k++;
yield return 0;
}
j++;
}
}
Holy crap is this how I should do things that take a while to compute but have nothing to do with game time?
Generally speaking, yes. Coroutines essentially let the engine know to come back to this spot on the next update loop. You can look at (http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html) for more information.
At a $$anonymous$$imum you've given me something that runs although I'm sure this task could be completed much faster than this code. Do you get karma simply by my having accepted your answer?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Keyboard to mouse click 0 Answers