2
\$\begingroup\$

Very simple question: If I'm going to be generating and placing a lot of 3d objects (in this case cubes), that are not going to be interactive, like no collision, no raycasting intersections etc. Should they be GameObjects or is there a lighter solution that doesn't inherit the GameObject blob?

Cheers,

\$\endgroup\$
1
\$\begingroup\$

GameObjects don't really prove to be that big of an overhead. Just make sure you are using a material with GPU Instancing enabled.

How to enabled GPU Instancing

However, if you want to avoid GameObjects anyway, you can instead use the Graphics class. Specifically Graphics.DrawMeshInstanced. You just need a reference to a Mesh and Material, as well as an array of matrices that indicate where to draw each one. Something like this:

public class DrawCubes : MonoBehaviour {
  public Mesh cube;
  public int submeshIndex;  //If the mesh has more than one submesh, specify which one to draw. Normally this can be left as 0.
  public Material material; //Note: This material must have instancing enabled.

  private Matrix4x4[] locations;
  void Start() {
    locations = new Matrix4x4[10];
    for (int i = 0; i < locations.length; ++i) {
      //Position at (i,0,0), no rotation, with no scaling
      locations[i] = Matrix4x4.TRS(new Vector3(i,0,0), Quaternion.identity, Vector3.one);
    }
  }
  void Update() {
    Graphics.DrawMeshInstanced(cube, submeshIndex, material, matrices);
  }
}

A few notes, from Unity's documentation:

Meshes are not further culled by the view frustum or baked occluders, nor sorted for transparency or z efficiency.

And

You can only draw a maximum of 1023 instances at once.

Also

InvalidOperationException will be thrown if the current platform doesn't support this API (i.e. if GPU instancing is not available). See SystemInfo.supportsInstancing.

If instancing is not supported, while you can still draw one at a time, using Graphics.DrawMesh, this is actually going to be less performant than using GameObjects, because this method does not use batching.

Finally, there are many overrides to DrawMeshInstanced to check out which add other features, like MaterialPropertyBlock overrides per instance.

\$\endgroup\$
  • \$\begingroup\$ Wow that's a fantastic answer, i'll dig into it when I have the chance! Thanks! \$\endgroup\$ – Danny F Jul 19 '18 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.