- Home /
What is the best way to change the color/material of objects individually?
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?
Answer by fffMalzbier · Dec 08, 2015 at 12:22 PM
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.
http://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html
Answer by wibble82 · Dec 08, 2015 at 12:32 PM
Hi
Material sharing is handled automatically by unity. If you have a mesh renderer, it has a 'material' and a 'sharedMaterial' property:
http://docs.unity3d.com/ScriptReference/MeshRenderer.html
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:
http://docs.unity3d.com/ScriptReference/Material.html
MeshRenderer myrenderer = GetComponent<MeshRenderer>();
myrenderer.material.SetFloat("_SomeFloatOnMyMaterial",10);
-Chris
Your answer
![](https://koobas.hobune.stream/wayback/20220612051657im_/https://answers.unity.com/themes/thub/images/avi.jpg)