Quick answer: GetComponent returns null when the requested component is not attached to the GameObject. This happens when the component was never added, was removed at runtime, or when you are calling GetComponent on the wrong GameObject.
Here is how to fix Unity nullreferenceexception getcomponent. You call GetComponent<Rigidbody>() and Unity throws a NullReferenceException on the very next line. The console points to a line where you use the reference, and the error message is frustratingly vague: "Object reference not set to an instance of an object." This is the single most common runtime error in Unity, and it almost always has the same handful of root causes. Let us walk through each one and fix them permanently.
The Symptom
Your script compiles without errors. You enter Play mode and immediately see one or more NullReferenceException errors in the Console. The stack trace points to a line where you access a variable that was assigned via GetComponent — something like rb.AddForce(Vector3.up) or anim.SetTrigger("Jump").
Double-clicking the error takes you to the script, and the variable declaration looks correct. You may have even assigned it in the Inspector and it looks fine there. But at runtime, the reference is null. Sometimes the error appears on the very first frame. Other times it appears only when a specific method runs, such as a collision callback or a coroutine that executes after a delay.
The error may also appear intermittently — working in one scene but failing in another, or working on one prefab instance but not on a duplicate. This inconsistency is a strong signal that the component is missing from some GameObjects but not others.
What Causes This
There are five common causes, roughly in order of frequency:
1. The component is not attached to the GameObject. This is the most frequent cause. You call GetComponent<Rigidbody>() on a GameObject that does not have a Rigidbody. Maybe you forgot to add it, removed it accidentally, or are referencing the wrong GameObject. Unity does not throw an error when GetComponent returns null — it only throws when you try to use that null reference.
2. Wrong lifecycle timing. You call GetComponent on another GameObject in Awake(), but that other object has not initialized yet. Unity calls Awake() on all objects before any Start() runs, but the order of Awake() calls between different objects is not guaranteed. If script A tries to find a component on script B’s object during Awake(), and script B creates that component in its own Awake(), the result depends on execution order.
3. Referencing a destroyed object. The component existed earlier but the GameObject was destroyed via Destroy(). After destruction, any cached reference becomes a "fake null" — Unity overrides the equality operator so the reference looks null but is not actually a C# null. Accessing members on it throws NullReferenceException or MissingReferenceException.
4. Using GetComponent on the wrong object. You call GetComponent on this.gameObject when the component is actually on a child, parent, or a completely different object. This is especially common with nested prefabs and UI hierarchies.
5. Serialized field reset. You assigned the reference in the Inspector, but Unity lost the serialized value — typically after reordering serialized fields, changing a field’s type, or renaming it. The Inspector shows "None" or "Missing," and the value is null at runtime.
The Fix
Step 1: Use RequireComponent to guarantee the component exists.
If your script fundamentally depends on another component being on the same GameObject, declare that dependency with the [RequireComponent] attribute. Unity will automatically add the component when your script is attached and will prevent it from being removed.
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class PlayerMovement : MonoBehaviour
{
private Rigidbody rb;
private CapsuleCollider col;
void Awake()
{
// These are guaranteed to succeed because of RequireComponent
rb = GetComponent<Rigidbody>();
col = GetComponent<CapsuleCollider>();
}
void FixedUpdate()
{
// Safe to use without null checks
rb.AddForce(Vector3.forward * 10f);
}
}
This is the strongest guarantee you can get. It eliminates the problem at the editor level before you ever enter Play mode. Use it for any component your script cannot function without.
Step 2: Cache references in the correct lifecycle method with null checks.
Use Awake() for references to components on the same GameObject. Use Start() for references to components on other GameObjects, because Start() runs after all Awake() calls are complete.
using UnityEngine;
public class EnemyAI : MonoBehaviour
{
private Animator anim;
private Transform playerTransform;
void Awake()
{
// Same-object reference: safe in Awake
anim = GetComponent<Animator>();
if (anim == null)
{
Debug.LogError($"Animator missing on {gameObject.name}", this);
}
}
void Start()
{
// Cross-object reference: use Start so the player's Awake has run
GameObject player = GameObject.FindWithTag("Player");
if (player != null)
{
playerTransform = player.transform;
}
else
{
Debug.LogWarning("No GameObject tagged 'Player' found in scene.");
}
}
void Update()
{
if (playerTransform == null) return;
// Safe to use now
Vector3 direction = (playerTransform.position - transform.position).normalized;
transform.LookAt(playerTransform);
}
}
Notice the pattern: cache the reference once, check it once, and then guard subsequent usage with a null check. The Debug.LogError with the second parameter (this) makes the error clickable in the Console, highlighting the exact GameObject that has the problem.
Step 3: Use TryGetComponent for safer, allocation-free lookups.
TryGetComponent was introduced in Unity 2019.2 and serves two purposes: it returns a boolean so you can branch cleanly, and in the editor it avoids the garbage allocation that GetComponent generates when the component is missing (due to Unity’s custom null check wrapper).
using UnityEngine;
public class PickupItem : MonoBehaviour
{
[SerializeField] private int healAmount = 25;
void OnTriggerEnter(Collider other)
{
// TryGetComponent returns false if the component is missing
if (other.TryGetComponent<PlayerHealth>(out var health))
{
health.Heal(healAmount);
Destroy(gameObject);
}
// Also works for interface-based lookups
if (other.TryGetComponent<IDamageable>(out var damageable))
{
damageable.TakeDamage(10);
}
}
}
This pattern is especially useful in collision and trigger callbacks where you do not know what type of object entered. Instead of calling GetComponent and checking for null, TryGetComponent combines both operations into a single, clean call.
Why This Works
RequireComponent shifts the check from runtime to edit-time. The component is guaranteed to exist because Unity enforces it at the moment the script is added. You cannot forget to add it and you cannot accidentally remove it.
Proper lifecycle ordering ensures that when you ask for a reference, the target has already initialized. The Awake → OnEnable → Start sequence is deterministic within a single object, and all Awake calls across the scene complete before any Start runs. Using the wrong method is like trying to read a book before it has been printed.
TryGetComponent avoids the custom Unity null-check overhead. In the editor, GetComponent on a missing component creates a temporary C++ wrapper object that immediately becomes garbage. TryGetComponent skips this, making it both safer and marginally faster when called frequently (such as in physics callbacks).
"If you have a NullReferenceException, do not ask what is null. Ask why it is null. The answer is almost always that the component was never there in the first place."
Related Issues
If your component exists but your coroutine stops unexpectedly before it can use the reference, see our guide on coroutines not starting or stopping early. If you are losing component references specifically on prefabs after editing, the prefab changes not saving article covers serialization pitfalls that can silently null out your Inspector assignments.
When in doubt, log it out. Debug.Log the variable right after GetComponent.