RUNTIME EXCEPTION • SCRIPTING
NullReferenceException: Object reference not set to an instance of an object
The single most common error in Unity game development. Learn how to locate the exact variable causing the crash and fix it permanently.
What It Means
Your script is trying to access a method, property, or field on a variable that points to null (nothing in memory). Because no object exists at that memory address, the .NET runtime halts execution of that method immediately.
Quick Fix Checklist
- Double-click the error in Unity Console to jump to the exact line in your code editor.
- Check if an
[SerializeField]Inspector slot is empty (showing None (Object)). Drag the asset into the slot. - Check if a
GetComponent<T>()call failed because the component isn't attached to that GameObject. - Add a safe null guard:
if (myObject != null) { myObject.DoSomething(); }
1
Incorrect vs Correct C# Code
SafeNullHandling.cs (C#)
using UnityEngine;
public class SafeNullHandling : MonoBehaviour
{
[Header("Assign in Inspector")]
[SerializeField] private AudioSource engineAudio;
[SerializeField] private Transform targetEnemy;
private Rigidbody rb;
private void Awake()
{
// SAFE INITIALIZATION: Always cache components in Awake
rb = GetComponent<Rigidbody>();
if (rb == null)
{
Debug.LogError($"[SafeNullHandling] Rigidbody component missing on {gameObject.name}!", this);
}
}
private void Update()
{
// ❌ BAD: Will throw NullReferenceException if targetEnemy was destroyed
// float dist = Vector3.Distance(transform.position, targetEnemy.position);
// ✅ GOOD: Null check before access
if (targetEnemy != null)
{
float dist = Vector3.Distance(transform.position, targetEnemy.position);
Debug.Log($"Enemy Distance: {dist}");
}
// ✅ MODERN C# NULL-CONDITIONAL OPERATOR:
engineAudio?.Play(); // Only calls Play() if engineAudio is not null
}
}
2
How to Prevent NullReferenceExceptions
- Use
[RequireComponent(typeof(Rigidbody))]: Forces Unity to automatically add the required component to the GameObject if you forget. - Check Destroyed References: In combat games (e.g. Operation Black Sky), enemies get destroyed mid-flight. Always verify
if (target != null)before guiding missiles.