# Thread: Help me with a loop

1. ## Help me with a loop

Hey guys. I find myself a little stumped on how to elegantly accomplish what I want to accomplish, and it might be just be because I'm tired, but I figured you all could prevent me from having to think!

I am experimenting with Unity optimizations of mesh combining, so that I can reduce my draw calls. I have two nested for loops to generate the objects, but this results in a long chain of objects and thus a long combined mesh. I want to reduce this approach to have a subgrid within my array of objects.

Here's how it is now... with one row of 64,000 or so vertices grouped into a large mesh.

And here's how I want it to be.

I'm thinking that this would be easy, but for some reason I'm not thinking of the solution right now. I'll sleep on it.

Here's a snippet of the code I'm using... it's just a simple double nested loop.

Code:
``` public void CreateCityChunk(int cityWidth, int cityLength, List<GameObject> buildingPrefabs)
{
GameObject cityChunk = CreateCityChunk();
int vertexCount = 0;

for (int y = 0; y < cityLength; y++)
{
for (int x = 0; x < cityWidth; x++)
{
if (vertexCount >= maxCombinedMeshVertexCount)
{
cityChunk = CreateCityChunk();
vertexCount = 0;

}
GameObject buildingObject = (GameObject) Instantiate(buildingPrefabs[Random.Range(0, buildingPrefabs.Count - 1)]);
buildingObject.transform.rotation = Quaternion.Euler(new Vector3(-90, 0, 0));
buildingObject.transform.position = new Vector3(x * (buildingObject.GetComponentInChildren<MeshFilter>().mesh.bounds.size.x + buildingSpacing),
0,
y * (buildingObject.GetComponentInChildren<MeshFilter>().mesh.bounds.size.y + buildingSpacing));
buildingObject.transform.parent = cityChunk.transform;
vertexCount += buildingObject.GetComponent<MeshFilter>().mesh.vertexCount;
}
}
foreach (GameObject chunk in CityChunks)
{
chunk.active = true;
}
}

private GameObject CreateCityChunk()
{
GameObject cityChunk = new GameObject();
cityChunk.name = string.Format("CityChunk{0}", CityChunkCount);
cityChunk.transform.parent = City.transform;
CityChunkCount++;
cityChunk.active = false;
return cityChunk;
}```
Thanks guys!

2. Actually it would make a lot more sense if it was...

I have something that mostly works as I asked above, but still fiddling with it in an incredibly zombified state of mind.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•