Change color without breaking batching Unity3D

448 Views Asked by At

I have a high number of objects in Unity, and I need to change their colors in real time (and several times). However, this breaks Unity batching, leading to very bad results in terms of performances. I am currently using the Standard pipeline.

I tried to use MaterialPropertyBlock, but it did not worked.

Someone can help me in solving this issue?

1

There are 1 best solutions below

10
KiynL On

The best solution to this problem is that instead of saving the material for each object and changing the parameters separately, you directly change the variable of the Shader. If you are using the Amplify Shader Editor, it is important to set the shader type to Global.

Cube Color

Parameter Type

In this example code, the color changes sinusoidally. It is enough to define the shader parameter ID in the static variable for maximum performance and change it with the Shader.SetGlobalColor method. And you don't need to have this code on every object. Just add it on one Manager and it's done.

public Color colorA = Color.cyan;
public Color colorB = Color.red;

// cache ID value because calling with string need heavier performance
private static readonly int CubeColor = Shader.PropertyToID("CubeColor");

void Update()
{
    // Change Directly Shader Global Color Value
    Shader.SetGlobalColor(CubeColor, Color.Lerp(colorA, colorB, (Mathf.Sin(Time.time) + 1) / 2));
}