Dynamic Batching/GPU Instancing in Unity

May 7, 2019

Dynamic Batching/GPU Instancing

Following Tutorial

Youtube – [Unity] GPU Instancing Tutorial

By: Blendcraft Creations

In Unity, the benefits of GPU instancing may not be imediately noticeable by the FPS alone in the editor. This first tutorial shows that the FPS is more properly represented in an actual build of the project. Even though this is an older Unity version, that is still good to note to test all the way through to see if you are getting the expected results.

Following this tutorial appeared to work as intended, but it did have a weird issue where I couldn’t create lower numbers of instances of objects. Upon inspecting the script, I determined that any number below 1000 most likely would not be rendered out based on the for loop creating the batches at start. The following code snippet is where the issue was occurring:

private void Start()
{
int batchIndexNum = 0;
List currBatch = new List();

for (int i = 0; i < instances; i++)
{
AddObj(currBatch, i);
batchIndexNum++;
if(batchIndexNum >= 1000)
{
batches.Add(currBatch);
currBatch = BuildNewBatch();
batchIndexNum = 0;
}
}
}

I amended this with a quick fix using a small snippet after the entire for loop as follows:

if(batchIndexNum != 0)
{
batches.Add(currBatch);
batchIndexNum = 0;
}

This allowed me to now render numbers of instances less than 1000, and theoretically allowed me to render instances of any amount now, where initially it would only render multiples of 1000.

I would need to do further analysis to really understand the processing benefits of this, but it is a nice start to at least see that it is working and creating many instances of an object for me. I was safely able to create a few thousand instances of simple objects and run the game in the editor for what it’s worth. I also added a very basic 3D player controller that mostly moved the camera around to get a better idea of how everything was running with all of these objects created.

Look Into – Coding
  • Graphics.DrawMeshInstanced()
  • Operator: =>