- Home /
Why does applying a material to a object break batching?
Why does applying a material to a object break batching?
Answer by robertbu · Sep 30, 2013 at 05:40 AM
Assigning a new material does not break batching. The object you assigned the new material will batch with other objects of that same new material. Here is a script you can run to verify. Attach it to an empty game object, drag and drop two or more materials into the materials array in the inspector, and hit run. Spacebar will advance to the next material. You should see that all the cubes are still batched even when the material is changed.
#pragma strict
var count = 100;
var materials : Material[];
private var iMat = 0;
private var objects : GameObject[];
function Start ()
{
objects = new GameObject[count];
for (var i = 0; i < count; i++) {
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.transform.localScale = Vector3(0.25, 0.25, 0.25);
go.transform.rotation = Random.rotation;
go.transform.position = Random.insideUnitCircle * 5;
go.renderer.material = materials[0];
objects[i] = go;
}
}
function Update()
{
if (Input.GetKeyDown(KeyCode.Space)) {
iMat = (iMat + 1) % materials.Length;
for (var i = 0; i < objects.Length; i++)
objects[i].renderer.material = materials[iMat];
}
}
What breaks batching is changing some property of the a material like texture, or color, or blending, or offset, or... If you change a property of the material, Unity creates a new material instance...it is no longer the same material. The reason it breaks batching is that the shader needs all the properties to be the same in order for the game objects to batch. For example a shader cannot handle two materials where the main color attribute is different at the same time.
Answer by reefwirrax · Sep 30, 2013 at 07:57 AM
you cannot batch 2 objects with 2 different materials, even if it's the same one, unless you use sharedMaterial.
unity free is less good at batching, there is a script somewhere that can textureAtlas multiple textures, but it is a tedious thing to do when you're trying to focus time on a game.
Not strictly true. The script above reassign a material without any reference to 'shared$$anonymous$$aterial,' and the objects continue to batch. The material is the shared material in the project since I've not made any changes at runtime, but I don't have to explicitly use 'shared$$anonymous$$aterial.'