I have a scene with hundreds of low-poly objects instantiated in real time from a prefab.
I’m looking for a way to change the color of them individually, at runtime (C#). If I change the material color, it applies to all objects. If I instantiate a new material for each object, I will probably be using a lot more resources than needed.
What would be a good approach to solve this problem?
I would recommend using the MaterialPropertyBlock.
MaterialPropertyBlock is used by Graphics.DrawMesh and Renderer.SetPropertyBlock. Use it in situations where you want to draw multiple objects with the same material, but slightly different properties. For example, if you want to slightly change the color of each mesh drawn.
Material sharing is handled automatically by unity. If you have a mesh renderer, it has a ‘material’ and a ‘sharedMaterial’ property:
The shared material should generally be left alone in code, and refers to the base material that is shared by all instances of the renderer.
The material property is conceptually unique to the object. I beleive unity does some clever stuff internally to avoid excessive memory use, but the key is, once you have it you can use the standard material property setters as documented here:
MeshRenderer myrenderer = GetComponent<MeshRenderer>();