# How many objects is too many?

I’m building a game demo where the ground is made up of small cubes that rearrange themselves as the player moves around.

The floor itself has 196 cubes but Unity seems to really struggle to put them on the screen, it takes a really long time for them to load and the frame rate drops to an unbearable crawl (<2fps).

I wonder what could be an efficient way of not only creating them but also handling their logic since their position is changing all the time and if Unity struggles to created them I don’t think it could handle that mane calculations every frame.

Here’s the code I used to create them, the logic for the cubes is already written but I haven’t tested it due to this problem.

``````//Create cubes
for (int z = 0; z < 14; z++)
{
for (int x = 0; x < 14; x++)
{
cube_transform[x,z] = Instantiate(transform,
new Vector3(RL.x + x_counter, floor, RL.z + z_counter ),
new Quaternion(0,0,0,0)) as Transform;
x_counter+=0.4f;
}
z_counter+=0.4f;
x_counter = 0;
}
return;
``````

Edit:
Something happened and Im not sure exactly what. The code is exactly the same as the one posted above but performance seems to have improved dramatically, going from under 2 fps to above 70. So I went ahead and tested my logic code to move the cubes around and…well Unity did not like it any more than the previous code and now it gets absolutely stuck when I hit play.

Am I supposed to be doing this another way?

Here’s basically how the code works (the create cubes above happens once at Start()).

``````void CheckFloor()
{
for (int z = 0; z < 14; z++)
{
for (int x = 0; x < 14; x++)
{
if (NeedsToMove(cube_position[x,z]))
{
MoveCube(cube_position[x,z], FindNewPosition(cube_position[x,z]));
}
}
}
}
``````

NeedsToMove returns a bool and it only checks if the distance from the cube to the center of the player is greater than a set distance.
MoveCube takes the cube that needs to be moved and moves it to the position determined by FindNewPosition.

Is this way too much logic to handle per frame?

That doesn’t make much sense. Unity should not struggle with 200 objects. Make sure your problem not somewhere else.

Check your draw calls, tris, and verts. Post them if you’d like. I don’t use C# so I probably won’t be much help, but make sure that you’re not endlessly generating cubes through Instantiate.

A better way would probably be to generate a “chunk” of cubes as a prefab instead of one at a time. Instantiating every frame would likely make it slow.

Thats all I can think of that would make this occur. Hope this helps.