Having 100 game objects with 100 behaviours each one running an own update function isn't actually that much, even on mobile. There might be some performance to gain by using the rather new Entity - Component - System architecture, but intuitively I am not that sure that this will even be necessary.
What could, however, become a bottleneck is if you update the color of each cube with GetComponent<Renderer>.material.color = new Color(r, g, b)
. Whenever you modify the material of a renderer, you actually create a completely new material in memory and assign that new material to this one object. This also breaks certain optimizations the rendering engine can do when multiple objects share the same material.
When you end up with 100 cubes which each have their very own material, then you might indeed run into performance problems.
So what should you do instead? That depends on what you actually want to do.
- If the number of colors you want is limited, then you could create a different material for each color and exchange those material assets.
- If all the cubes are supposed to change their color at the same time, you can access the
.sharedMaterial
of one of them to also change all the other (which of course won't work if you already broke the material sharing as described above)
- If you want to assign arbitrary colors to each cube, use
renderer.SetPropertyBlock
. This very useful method allows you to override just a few settings of a material on a per-renderer base without breaking the draw call optimization you got from sharing materials.
Example code:
MaterialPropertyBlock properties = new MaterialPropertyBlock();
properties.AddColor("_Color", new Color(r, g, b));
GetComponent<Renderer>().SetPropertyBlock(properties);
cubes
game object, grab reference to thatcubes
object in script and loop through every child objects and change their materials. However it may not be that performance efficient \$\endgroup\$ – Digvijaysinh Gohil Apr 6 at 12:36var
are not your limiting factors here - that's more likely to come from draw call overhead from breaking batching. \$\endgroup\$ – DMGregory♦ Apr 6 at 12:44