- Home /
Batch Objects with Different Colors and Scales
I am fairly new to Unity so this may be my own simple failure but I am currently converting an XNA game to Unity. I have about 8000 objects that need to use the same texture but have random colors and scale that constantly change.
I have noticed that nothing is getting batched and have determined it is because of the different colors/scales.
How can I have objects with different colors and scales still be batched together?
Answer by ytao · Dec 22, 2011 at 07:27 AM
The failure of batching is most likely the material color. If you have ever modified any properties of a material, like color, uv, it will create an instance of the material. You can verify this by checking the [Material] field of the GameObject in the Hierarchy view at run time, and you should see "(Instance)" at the end of each material name.
The "bucket" technique may be helpful. You need to limit the random set (namely infinite) to some finite set. For instance, pre-create 100 random colors and choose from them to simulate random effect. Then, pre-create 100 materials for these colors and every object will be linked to one of them. So, objects that "falls" to the same bucket (color) will share the same material and will be batched accordingly.
I isolated both color and scale, because I didn't believe scaling was a problem either, and have found they both cause objects to not batch. The color I understand but scaling I do not. I think it may be because the scaling is very dynamic and changes essentially every frame but I don't understand how it's not batching because the material is not instanced.
you can do it in shaderlanguage if you dont need to send the color info every frame to shader, overlay a color on a shader.
also around here is a question from zoomdomain saying how to batch colors by changing uv's of each mesh and using the same multicolor texture on all them.
Answer by reefwirrax · Dec 30, 2013 at 07:59 PM
Renderer.SetPropertyBlock.
Unity's terrain engine uses MaterialPropertyBlock to draw trees; all of them use the same material, but each tree has different color, scale & wind factor. The block passed to Graphics.DrawMesh or Renderer.SetPropertyBlock is copied, so the most efficient way of using it is to create one block and reuse it for all DrawMesh calls. Use Clear to clear block's values, and AddFloat, AddVector, AddColor, AddMatrix to add values.
$$anonymous$$y tests show that using $$anonymous$$aterial Property Blocks achieves (at best) the same performance as using different materials (but the same shader).