Hi, I need some feedback on the following situation. I already have a solution in mind but I am unsure if that is the proper way to go forward with this.
For the sake of simplicity lets say I have a cube prefab. I created a custom shader for it.
Now lets say I have two cubes and I want them both to use the same shader/material, but each cube should have different color. I have achieved this by setting in the editor a new material instance for each cube like this :
Renderer rend = _gameobject.GetComponent<Renderer>();
Material temp_Mat = new Material(rend.sharedMaterial);
temp_Mat.SetColor(shader_ID, color);
Undo.RecordObject(rend, "dd");
rend.sharedMaterial = temp_Mat;
The problem with this is that unity creates a separate draw call for each material instance. Thus for performance sake I found this alternative :
Renderer rend = _gameobject.GetComponent<Renderer>();
MaterialPropertyBlock matBlock = new MaterialPropertyBlock();
matBlock.SetColor(shader_ID, color);
Undo.RecordObject(rend, "dd");
rend.SetPropertyBlock(matBlock);
The problem with this is that on play mode the new cube colors revert back to the ones set originally in the common material. If however I set the color values inside the start method the colors will stick for the duration of play mode.
Now my question is if this approach of setting the colors on start every time a good one? It seems like a big hastle for something so simple. If I could just tell Unity to not erase the data on start…
I like that “sharedMaterial” does not erase the color data on start, but “MaterialPropertyBlock” and “SetPropertyBlock” are more efficient… so which one is the better way to go ?