There are 64k cubes, 64k-1 's materials are assigned to sharedMaterial of first cube. But unity is not batching them together. Only cubes themselves are batched.
- Static color(but different per cube)
- Dynamic position and rotation per cube
How can I force unity to batch them all so it sends all cube data with only an array then draw once instead of drawing 64k times?
Each cube has a constructor as:
public class Test : MonoBehaviour {
public static System.Random r { get; set; }
// Use this for initialization
public static Material m=null;
void Start () {
if (r == null)
r = new System.Random();
sayac++;
if (m == null)
m = GetComponent<Renderer>().sharedMaterial;
else
GetComponent<Renderer>().material = m;
GetComponent<Renderer>().material.color = new Color((float)r.NextDouble(), (float)r.NextDouble(), 1);
var mesh= GetComponent<MeshFilter>().mesh;
var vertices = mesh.vertices;
var colors = new Color[vertices.Length];
var i = 0;
while (i < vertices.Length)
{
colors[i] = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble());
i++;
}
mesh.colors = colors;
mesh.UploadMeshData(false);
mesh.Optimize();
}
}
and they are instantiated from a cube as:
for(int i=0;i<1024*64;i++){
var pos = new Vector3(i % 64, (i /64) % 64, (i / 4096) % 64);
pos*=2.5f;
var cu = Instantiate(ref_cu, pos, Quaternion.identity);
cu .name = "cube_" + i;
}
After deleting 'material.color' lines, batching has started. But now cubes are not easily seen as with different colors. I need them different colored but not changing. Static color but different per cube. How it looks now:
its not easy to see individual cubes.
public class Test : MonoBehaviour {
public static System.Random r { get; set; }
// Use this for initialization
public static Material m=null;
void Start () {
if (r == null)
r = new System.Random();
sayac++;
if (m == null)
m = GetComponent<Renderer>().sharedMaterial;
else
GetComponent<Renderer>().material = m;
}
}


GetComponent<Renderer>().material.colorcreates a copy of the material for every instance. \$\endgroup\$ref_cuprefab. Check itsMeshRenderercomponent in the inspector. As an aside, any reason you're constructing a newSystem.Randominstance for every cube instead of having them use Unity's staticRandomclass? \$\endgroup\$