Course contentsShow
← Unity Game Development
Lesson 215 of 8283. Physics and InteractionFree lesson

Batching Physics Queries to Reduce Overhead

Learners will implement non-allocating physics query methods to minimize garbage collection and improve performance during frequent raycasting operations.

In this lesson, you will learn how to replace standard physics queries with "non-allocating" versions to keep your game running smoothly by reducing garbage collection.

The Problem with Standard Queries

When you perform frequent checks, such as using Physics.Raycast or Physics.OverlapSphere, Unity often returns an array of hits. Under the hood, this creates a new array object in your computer's memory every time the code runs. If you are doing this 60 times per second for multiple objects, these "allocations" pile up. Eventually, the Garbage Collector (GC) must step in to clean up this "trash," which causes those annoying micro-stutters or frame drops in your game.

The Solution: Non-Allocating Methods

Instead of asking Unity to create a new array for you, you can provide your own pre-allocated array (or NativeArray) that Unity simply fills with data. This "batching" approach reuses the same memory space, meaning zero new garbage is created.

To implement this, we use the "NonAlloc" variants of our common physics methods. Here is how you might optimize a radar-like scan:

// Define a buffer once at the class level to reuse it
private RaycastHit[] _hitBuffer = new RaycastHit[5];

void Update()
{
    // Use RaycastNonAlloc to fill the pre-existing _hitBuffer
    // This creates zero garbage!
    int hitCount = Physics.RaycastNonAlloc(transform.position, transform.forward, _hitBuffer, 10f);

    for (int i = 0; i < hitCount; i++)
    {
        Debug.Log("Hit object: " + _hitBuffer[i].collider.name);
    }
}

Why This Matters

By using RaycastNonAlloc, OverlapSphereNonAlloc, or BoxCastNonAlloc, you take control of memory management. You define the maximum number of objects you care about (the size of your array), and Unity updates that existing buffer. This is significantly more efficient than letting the engine allocate temporary memory that the Garbage Collector has to clean up later. As your projects grow in complexity, keeping your heap memory clean is a vital habit for maintaining a high, stable frame rate.

Key Takeaway: Use "NonAlloc" physics methods and pass in pre-allocated arrays to eliminate runtime garbage collection and keep your physics performance consistent.