- Home /
for loop crash...
Vector3 gridStart = transform.position - new Vector3(worldX, worldY, worldZ);
for(float x =0F; x<worldX; x += snap) {
Debug.Log (x);
for(float y =0F; y<worldY; y += snap) {
for(float z =0F; z<worldZ; z += snap) {
GameObject gridCube = Instantiate(prefab) as GameObject;
Vector3 startPosition = transform.position + new Vector3(worldX, worldY, worldZ);
gridCube.transform.position = new Vector3(gridStart.x + x, gridStart.y, gridStart.z + z);
gridCubesList.Add(gridCube);
gridCubes = gridCubesList.ToArray();
}
}
}
So this code totally freezes my editor. What's the problem?
Answer by gjf · Oct 23, 2014 at 09:51 AM
what are the values of worldX/Y/Z? if they're not small, it's likely that it's just taking a very long time...
... especially if you're converting the list to an array EVERY iteration...
you don't need to do that at all - you can index the list like an array.
@Avash:
Yep it depends on your worldXYZ size and what "snap" is set to.
Example if your world is 10 / 10 / 10 and snap is 1 you will have 1000 iterations and thousand cubes (that will already take quite a while).
But if you would use 0.1 for "snap" you will have 1000000 iterations and if it's 2 you only have 125 iterations. Also since you'll probably end up with a lot of elements in your list you should set the list's Capacity to the number of elements expected before the loop, so it doesn't get resized. If you really need the list as array, do it after the loop, once.
Should that be something like $$anonymous$$ecraft? If so you're completely on the wrong track ;) You can't instantiate millions / billions single cubes.
I'm just trying to code a grid solution... I want it to work with big objects.
Your answer
![](https://koobas.hobune.stream/wayback/20220613165743im_/https://answers.unity.com/themes/thub/images/avi.jpg)