Course contentsShow
← Unity Game Development
Lesson 575 of 8288. Artificial IntelligenceFree lesson

Optimizing Rendering with GPU Instancing and Culling

Apply GPU instancing and frustum culling techniques to render thousands of individual NPC meshes while keeping draw calls within performance budgets.

In this lesson, you will learn how to render thousands of individual NPC meshes efficiently by leveraging GPU instancing to collapse draw calls and frustum culling to skip unnecessary processing.

The Problem: Draw Call Bottlenecks

When you have a crowd of hundreds or thousands of NPCs, your CPU spends most of its time telling the GPU to "draw this mesh, then draw that mesh." If every NPC is a unique draw call, your frame rate will plummet before your AI even finishes its logic. GPU Instancing solves this by sending one mesh and a buffer of unique data (like position, rotation, and animation frame) to the GPU, allowing the graphics card to draw the entire crowd in a single batch.

Implementing Instancing

To enable this, your shader must support instancing. You simply check the "Enable GPU Instancing" box on your material. In your C# script, you can use Graphics.DrawMeshInstanced to manually handle large groups, though the easiest path is ensuring your NPC prefabs use an Instanced-compatible shader.

Saving Cycles with Frustum Culling

Rendering an NPC that is behind the camera is a waste of resources. While Unity handles basic culling automatically, when using custom instanced rendering, you must ensure you are not submitting data for NPCs outside the camera's view. You can calculate this by checking if an NPC's bounding box intersects with the camera's GeometryUtility.CalculateFrustumPlanes.

// Example of checking visibility before adding to an instance buffer
if (GeometryUtility.TestPlanesAABB(cameraPlanes, npcCollider.bounds))
{
    instanceDataList.Add(matrix); // Add only visible NPCs to the GPU buffer
}
Graphics.DrawMeshInstanced(mesh, 0, material, instanceDataList);

By combining these, you keep the CPU light—only managing the AI logic and visibility checks—while the GPU handles the heavy lifting of rendering the mass geometry. This allows your GOAP-driven agents to exist in massive, dense crowds without crippling your performance budget.

Key Takeaway: Use GPU Instancing to reduce the number of draw calls by grouping identical meshes, and combine it with custom Frustum Culling to ensure the GPU only processes the NPCs currently visible to the player.