Course contentsShow
← Unity Game Development
Lesson 82 of 8282. Scripting and LifecycleFree lesson

Optimizing Component Lookups via Cached References

Understand why calling GetComponent inside the Update method is performance-heavy and learn to store references in variables during initialization.

In this lesson, you will learn why repeatedly searching for components in your Update method slows down your game and how to fix it by caching them in a variable.

The Problem: Searching Every Frame

In previous lessons, you learned how to use GetComponent to grab a reference to a script or component. You might be tempted to call it directly inside the Update method, like this:

void Update() {
    // This runs every single frame!
    GetComponent<Rigidbody>().AddForce(Vector3.up);
}

While this works, it is inefficient. Every time Update runs (which can be 60 or more times per second), Unity has to pause and search through every single component attached to your GameObject to find the Rigidbody. This is a "heavy" operation because it creates unnecessary work for your processor.

The Solution: Caching

Instead of searching for the component repeatedly, you should perform the search exactly once during the initialization phase and save the result in a variable. By storing the reference, you can access that component instantly whenever you need it.

Using Awake or Start is the perfect place to do this:

private Rigidbody rb; // 1. Create a variable to hold the reference

void Start() {
    // 2. Find it once and store it
    rb = GetComponent<Rigidbody>();
}

void Update() {
    // 3. Reuse the stored reference every frame
    rb.AddForce(Vector3.up);
}

By caching the Rigidbody in the rb variable, your Update method no longer needs to hunt for the component. It simply looks at the reference you already saved. This keeps your game running smoothly because your script isn't wasting time on repetitive lookups.

This pattern is a fundamental optimization technique. Whether you are grabbing a Renderer, a Collider, or your own custom scripts, always perform the lookup during initialization and save the reference for later use.

Key Takeaway: Never call GetComponent inside Update; instead, find your component once in Awake or Start and store it in a variable to boost performance.