Quick answer: MissingReferenceException means a C# variable still points at a Unity object whose native side was removed by Destroy or a scene unload. Something outlived the object: an event subscription, a coroutine or async method, a cached list entry, a tween. Unsubscribe in OnDisable, cancel async work with destroyCancellationToken, clear cached references, and test with == null, never ?. or is null.
The Console says the object has been destroyed but you are still trying to access it, and the line it points at looks innocent: a transform read, a SetActive call, a text update. The mistake is somewhere else, in whatever kept a reference alive after the object died. This guide explains why a destroyed Unity object is not a real C# null, lists the places a stale reference usually hides, shows how to read the stack trace to find the holder, and gives before and after code for each case. Everything here applies to Unity 6 and 2022 LTS.
- The exact error
- Why a destroyed object is not null
- What causes it
- How to find what is holding the reference
- Fix 1: unsubscribe from every event
- Fix 2: stop async methods and coroutines with the object
- Fix 3: keep persistent objects from holding scene objects
- Fix 4: Destroy timing, tweens and UI listeners
- The editor-only variant: leaving or re-entering play mode
- How to confirm the fix
- Seeing it when it happens to players
- Related guides
- Frequently asked questions
The exact error
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
The type in quotes is the type of the dead object, so you will also see 'Transform', 'Image' or the name of one of your own scripts. Unity 6 prints the full type name, for example 'UnityEngine.GameObject'. A second form appears when an Inspector field pointed at something that was deleted:
MissingReferenceException: The variable target of CameraFollow doesn't exist anymore.
Both mean the same thing: the C# variable is not empty, but the engine object behind it is gone. The exception type exists only in the editor. In a player build the same access throws a plain NullReferenceException, which Unity confirms in its support article on the two exceptions. A build-only NullReferenceException in code that touches spawned or scene objects is very often this bug.
Why a destroyed object is not null
Every UnityEngine.Object (GameObject, component, ScriptableObject) is a small C# wrapper around a native engine object. Destroy frees the native object. The C# wrapper stays alive for as long as any variable, list, delegate or closure still references it. Unity overloads ==, != and the conversion to bool so that such a wrapper compares equal to null. C# operators that cannot be overloaded look only at the C# reference, which is still there.
| Check on a destroyed object | Result |
|---|---|
obj == null | true (Unity’s operator) |
if (obj) or obj != null | false, correctly reports it as gone |
obj is null, obj is not null | Treats it as alive |
obj?.DoThing() | Calls DoThing, which then throws |
obj ?? fallback, obj ??= x | Keeps the destroyed object |
ReferenceEquals(obj, null) | false |
The same object stored in an interface or object variable, compared with == | false, because the overload is not used |
Destroy(enemy); // enemy is a GameObject
// one frame later:
if (enemy == null) { } // true
if (enemy is null) { } // false
enemy?.SetActive(false); // runs SetActive and throws MissingReferenceException
This is also the difference from the two neighbouring errors. A NullReferenceException means the variable never held anything, or holds a real null. An UnassignedReferenceException means an Inspector slot was left empty. A MissingReferenceException means the variable held a real object and that object was destroyed later.
What causes it
- An event subscription that was never removed. A HUD element does
player.HealthChanged += OnHealthChangedinStartand is destroyed on a scene change. The player, or a static event, still holds the delegate and calls into the dead HUD the next time health changes. This is the most common cause. - An async method that kept going.
await Task.Delay(2000)resumes whether or not the object still exists. Unity does not cancel tasks when an object is destroyed or when you leave play mode. - A coroutine on one object that uses another. A coroutine stops when its own MonoBehaviour is destroyed, but a coroutine running on a manager keeps running after the enemy it was following is gone.
- A
DontDestroyOnLoadsingleton caching scene objects. The GameManager stores the player, the camera or a UI panel in a field, the scene reloads, and the fields now point at the previous scene’s objects. - A list or dictionary of spawned objects that is never pruned. Enemies are added to
activeEnemieson spawn and destroyed on death, and nothing removes them from the list. - Assuming
Destroyclears your variable. It does not, and it does not act until the end of the frame, so a null check in the same frame still passes. - Tweens and UI listeners. A DOTween tween on a destroyed transform, or a
button.onClick.AddListenercall whose target was destroyed while the button lives on.
How to find what is holding the reference
Read the stack trace from the top down. The first line is the engine call that noticed the object was dead. The first line in your own code is where the dead object was used. The lines below that say who called it, and that caller is the holder.
MissingReferenceException: The object of type 'HealthBar' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Component.get_transform () (at <hash>:0)
HealthBar.OnHealthChanged (System.Int32 hp) (at Assets/Scripts/UI/HealthBar.cs:27)
PlayerHealth.TakeDamage (System.Int32 amount) (at Assets/Scripts/PlayerHealth.cs:41)
Spike.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Spike.cs:12)
Here HealthBar is the destroyed object, and PlayerHealth.TakeDamage called its handler, so the holder is an event on PlayerHealth. The frames under your method identify the other cases:
| Frames below your method | What is holding the reference |
|---|---|
| A method of another class that raises an event | A C# event or delegate subscription |
UnityEngine.Events.UnityEvent.Invoke | A UnityEvent listener, usually a Button onClick |
<SomeRoutine>d__4.MoveNext then UnityEngine.SetupCoroutine.InvokeMoveNext | A coroutine |
MoveNext then UnityEngine.UnitySynchronizationContext | An async method resuming after an await |
Frames in the DG.Tweening namespace | A DOTween tween or callback |
Your own Update or a loop over a collection | A cached field or a list entry |
If the trace is not enough, log the destruction and compare timing. Debug.Log($"{name} destroyed, frame {Time.frameCount}", this) in OnDestroy, next to a similar log at the failing line, tells you whether the access came the same frame, a few frames later, or after a scene load. That narrows it to deferred destruction, a delayed callback, or a persistent holder.
Fix 1: unsubscribe from every event
// Before
public class HealthBar : MonoBehaviour
{
[SerializeField] PlayerHealth player;
[SerializeField] Transform fill;
void Start()
{
player.HealthChanged += OnHealthChanged; // never removed
}
void OnHealthChanged(int hp)
{
fill.localScale = new Vector3(hp / 100f, 1f, 1f);
}
}
// After
void OnEnable() { player.HealthChanged += OnHealthChanged; }
void OnDisable() { player.HealthChanged -= OnHealthChanged; }
OnDisable runs when the object is deactivated and also when it is destroyed, just before OnDestroy, so the pair covers both. Unsubscribing is safe even if the publisher was destroyed first, because an event is a plain C# field and touching it makes no engine call.
Two traps. A lambda cannot be unsubscribed: player.HealthChanged += hp => Refresh(hp) creates a delegate you have no handle to, so use a named method or keep the delegate in a field. A static event lives for the whole run of the game, so every subscriber that can be destroyed must remove itself.
Fix 2: stop async methods and coroutines with the object
// Before
async void Start()
{
await Task.Delay(2000);
gameObject.SetActive(false); // the object may be gone by now
}
// After (Unity 2022.2 and later)
async void Start()
{
try
{
await Task.Delay(2000, destroyCancellationToken);
gameObject.SetActive(false);
}
catch (OperationCanceledException) { }
}
MonoBehaviour.destroyCancellationToken was added in Unity 2022.2 and is cancelled when the component is destroyed. In Unity 6 the same pattern works with await Awaitable.WaitForSecondsAsync(2f, destroyCancellationToken). On older versions, put if (this == null) return; after every await.
In a coroutine that uses other objects, check them again after each yield, because any number of frames may have passed:
IEnumerator Follow(Transform target)
{
while (target != null)
{
transform.position = Vector3.MoveTowards(
transform.position, target.position, speed * Time.deltaTime);
yield return null;
}
}
Fix 3: keep persistent objects from holding scene objects
Anything marked DontDestroyOnLoad outlives the scene, so it must not keep direct references to scene objects unless those objects tell it when they go away. Have each object register and unregister itself:
public class Enemy : MonoBehaviour
{
void OnEnable()
{
EnemyRegistry.Instance.Register(this);
}
void OnDisable()
{
if (EnemyRegistry.Instance != null)
EnemyRegistry.Instance.Unregister(this);
}
}
For a cache you cannot restructure today, prune it when the scene changes and before use:
void OnEnable() { SceneManager.sceneLoaded += OnSceneLoaded; }
void OnDisable() { SceneManager.sceneLoaded -= OnSceneLoaded; }
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
activeEnemies.RemoveAll(e => e == null); // Unity's == catches destroyed entries
player = null; // found again on demand
}
If Unregister runs while the registry is looping over its list, you trade this error for Collection was modified. That guide covers safe removal during iteration.
Fix 4: Destroy timing, tweens and UI listeners
Destroy removes the object after the current Update loop, before rendering. Until then the object still works and != null is still true. It also never changes your variables. Clear them yourself, and remember that other scripts with their own copy still hold the object.
Destroy(currentWeapon);
currentWeapon = null;
DOTween tweens are owned by DOTween, not by the object they animate. Link the tween so it is killed with the object, or kill it in OnDestroy:
transform.DOMove(target, 0.5f).SetLink(gameObject);
void OnDestroy() { transform.DOKill(); }
DOTween’s safe mode, on by default, catches the failure for you. With safe mode off you get the exception. Listeners added from code need the same care as C# events: a button.onClick.AddListener(OnClick) call needs a matching RemoveListener in OnDestroy when the button outlives the listener.
The editor-only variant: leaving or re-entering play mode
Three situations produce this error only in the editor.
- Domain reload is disabled. With Edit > Project Settings > Editor > Enter Play Mode Settings set to skip the domain reload, static fields and static events keep their values between play sessions. Subscribers from the previous session are destroyed objects, and the first time the event fires it calls them. Reset statics explicitly:
public static event Action<int> ScoreChanged; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetStatics() { ScoreChanged = null; } - A task finishes after you press Stop. Tasks keep running when play mode ends, then touch objects that no longer exist.
destroyCancellationTokenfixes it;Application.exitCancellationTokencovers code that is not on a MonoBehaviour. OnDestroyreaches for another object during teardown. When a scene unloads, the order in which objects are destroyed is not something to rely on. Null-check the other object, and do not let a lazy singleton getter create a new GameObject fromOnDestroy, which produces the separate warning “Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)”.
How to confirm the fix
Repeat the sequence that kills the object, then trigger whatever used it: destroy the enemy and deal damage, reload the scene twice and fire the event, stop play mode while a delay is pending. Run once with domain reload disabled, since that exposes leftover static subscribers immediately. Then make a development build, play the same path and search Player.log for NullReferenceException, because that is the name this bug has outside the editor.
Seeing it when it happens to players
In a shipped build this bug has no special name and no hint about which object died. It is a NullReferenceException with a stack trace. The Bugnet Unity SDK listens to Application.logMessageReceived and files each exception as a report with that stack trace, the recent log lines, platform, OS version and game version, once per distinct message per session. Reports with the same title stack into one entry with an occurrence count, so a stale event subscription that fires for many players shows up as one busy item, not a flood. What Bugnet cannot do is tell you which object was destroyed. That still comes from reading the frames as described above, so enable IL2CPP Stacktrace Information with line numbers if your release builds use IL2CPP. The bug reports guide shows what a filed report contains.
Related guides
- How to Fix Unity’s NullReferenceException
- How to Fix UnassignedReferenceException in Unity
- How to Fix “MissingComponentException: There is no ‘Rigidbody’ attached to the game object” in Unity
- Fix: Unity Async Await Task Leak After Scene Unload
- How to Fix a Unity GameManager Instance Going Null After Unloading an Additive Scene
Frequently asked questions
What does MissingReferenceException mean in Unity?
A script used a Unity object after it was destroyed. The C# variable still refers to the old wrapper, but the engine object behind it was removed by Destroy or by a scene unload. The fix is to stop whatever kept using it, usually an event subscription, a coroutine, an async method or a cached list.
Why does my null check pass but the object still throws MissingReferenceException?
You probably used the null-conditional operator, the null-coalescing operator or the is null pattern. Those look at the C# reference, which still exists. Only Unity’s own equality operators and the implicit bool conversion know the object was destroyed, so write the check with == null or != null.
Why is it a NullReferenceException in my build but a MissingReferenceException in the editor?
MissingReferenceException is an editor-only diagnostic. The editor stores extra information so it can name the destroyed type. Player builds skip that work and throw a plain NullReferenceException for the same access, so treat both as the same bug.
Does Destroy set my variable to null?
No. Destroy removes the engine object at the end of the current frame and leaves every C# variable that referred to it untouched. Set your own field to null after calling Destroy, and make sure other scripts holding a copy are told the object is gone.
How do I stop an async method when its GameObject is destroyed?
In Unity 2022.2 and later, pass the destroyCancellationToken property of the MonoBehaviour to the awaited call and catch OperationCanceledException. On older versions, check whether this equals null after every await and return if it does.
The line in the error is where the dead object was used. The bug is in whatever still held it, so read down the stack trace to the caller before you add a null check.