Tips/Tip #001 — Cache Component References in Frequently Called Unity Code

Cache Component References in Frequently Called Unity Code

When code runs for many units or every frame, cache component references instead of repeatedly searching for the same component.

The simple rule

If you already know which component an object needs, keep a reference to it and reuse that reference. Avoid repeating component lookups inside hot paths such as Update(), movement loops, or code that processes many units.

Instead of searching repeatedly

void Update()
{
    var agent = GetComponent<UnitAgent>();
    agent.Move();
}

Cache the reference once:

private UnitAgent _agent;

void Awake()
{
    _agent = GetComponent<UnitAgent>();
}

void Update()
{
    _agent.Move();
}

Why it matters

A single lookup may not matter. Repeating it across hundreds of objects and many frames can create unnecessary work. Caching is especially useful when a system updates a large group of units, enemies, projectiles, or UI elements.

Quick takeaway

Get the reference once when the object is initialized, then reuse it in frequently called code.