I have millions of objects that I want to render. I found that instantiate is not suitable, so I'm using Graphics.RenderMesh which is amazingly fast and light. But here comes the problem: it takes CPU resources because we are using a loop for each object and then rendering it:
void DrwaTree(Vector3 position, Quaternion rotation, Vector3 scale)
{
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, scale);
for (int i = 0; i < materials.Length; i++)
{
RenderParams rp = new RenderParams(materials[i]);
rp.shadowCastingMode = TreeShadowCasting[i];
Graphics.RenderMesh(rp, TreeMesh, i, matrix);
}
}
This function is called a million times in different scripts with different meshes. I want to find a way to make it less CPU-intensive.
One current approach I am applying is to bring different objects under a common center point (multiple center points for different objects). Then, I calculate the distance between the center point and the camera position to execute a specific loop only for objects near the camera. Is there any alternative or more appropriate approach?