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

Enforcing Safe Communication with Null Checking

Develop defensive programming habits by validating object references before access to prevent runtime errors when components are destroyed or missing.

In this lesson, you will learn how to prevent your game from crashing by validating object references before you attempt to use them.

The "Null Reference" Trap

In Unity, you often store references to other components or GameObjects. However, what happens if that object is destroyed, or if you forgot to drag it into the Inspector? If your script tries to access a component on an object that no longer exists or was never assigned, Unity throws a NullReferenceException. This stops your code execution immediately and creates bugs that are frustrating to track down.

Validating Your References

Defensive programming means assuming that a reference might be missing and checking it before you try to use it. In C#, we use the null keyword to represent an empty reference. By wrapping your logic in a simple if statement, you ensure your code only runs when the target is safe to access.

Consider this script that tries to change the color of a light:

public Light targetLight;

void Update()
{
    // Check if the reference is assigned and not destroyed
    if (targetLight != null)
    {
        targetLight.intensity = 5.0f;
    }
    else
    {
        Debug.LogWarning("Target light is missing! Skipping logic.");
    }
}

Why This Matters

If you try to access targetLight.intensity without the if check and the variable is empty, your entire Update method will crash for that frame. By using if (targetLight != null), you create a safety buffer.

This habit is especially important when handling objects that might be destroyed during gameplay, such as enemies or projectiles. Even if you cached your reference using GetComponent earlier, that reference can become "null" the moment the object is removed from the scene. Checking for null allows your game to stay resilient, even when objects disappear unexpectedly.

Key Takeaway: Always check if your object references are null before accessing their properties to prevent runtime crashes and ensure stable communication between your game systems.