Destroyed Objects & Fake Null
Every Unity object you touch from C# (a GameObject, a component, a material, a texture) is two objects: a native object inside the C++ engine and a managed C# wrapper that points to it. Destroy frees the native side. The C# wrapper lives on until the garbage collector removes it, and your variables still point at it.
To hide that, UnityEngine.Object overloads == and !=: a destroyed object compares equal to null even though the reference isn't null. This is called fake null, and it is behind some of the most confusing Unity bugs.
The model
The class below copies Unity's trick: it has a "native" handle and an overloaded == that checks whether the handle is still alive.
using System;
var enemy = new UnityObject("Enemy");
UnityObject.Destroy(enemy);
Console.WriteLine(quot;enemy == null -> {enemy == null}"); // overloaded ==
Console.WriteLine(quot;enemy is null -> {enemy is null}"); // real reference check
Console.WriteLine(quot;(object)enemy == null -> {(object)enemy == null}");
Console.WriteLine(quot;enemy?.Name -> {enemy?.Name ?? "(null)"}"); // ?. ignores the overload
Console.WriteLine(quot;bool(enemy) -> {(bool)enemy}"); // Unity's implicit bool
UnityObject? target = enemy;
UnityObject chosen = target ?? new UnityObject("Fallback"); // ?? ignores the overload too
Console.WriteLine(quot;target ?? fallback -> {chosen.Name}");
try { enemy.Ping(); }
catch (InvalidOperationException e) { Console.WriteLine(quot;enemy.Ping() -> {e.Message}"); }
class UnityObject
{
public string Name;
bool nativeAlive = true; // stands in for the C++ object
public UnityObject(string name) => Name = name;
public static void Destroy(UnityObject o) => o.nativeAlive = false;
public void Ping()
{
if (!nativeAlive) throw new InvalidOperationException(quot;The object of type 'UnityObject' has been destroyed but you are still trying to access it.");
Console.WriteLine(quot;{Name} pong");
}
static bool IsNull(UnityObject? o) => o is null || !o.nativeAlive;
public static bool operator ==(UnityObject? a, UnityObject? b) =>
IsNull(a) && IsNull(b) || ReferenceEquals(a, b);
public static bool operator !=(UnityObject? a, UnityObject? b) => !(a == b);
public static implicit operator bool(UnityObject? o) => !IsNull(o);
public override bool Equals(object? obj) => obj is UnityObject u && this == u;
public override int GetHashCode() => Name.GetHashCode();
}enemy == null -> True
enemy is null -> False
(object)enemy == null -> False
enemy?.Name -> Enemy
bool(enemy) -> False
target ?? fallback -> Enemy
enemy.Ping() -> The object of type 'UnityObject' has been destroyed but you are still trying to access it.
Unity's real exception is MissingReferenceException with almost the same message. The important lines are ?. and ??: they check the C# reference, not the overloaded ==, so they happily use a destroyed object.
What this means in Unity code
using UnityEngine;
public class Homing : MonoBehaviour
{
[SerializeField] Transform target;
void Update()
{
// WRONG: ?. does not see that the target was destroyed -> MissingReferenceException
// Vector3? aim = target?.position;
// RIGHT: the overloaded == / implicit bool knows about destroyed objects
if (target == null) { FindNewTarget(); return; }
// or: if (!target) { ... }
transform.position = Vector3.MoveTowards(transform.position, target.position, 8f * Time.deltaTime);
}
void FindNewTarget() { /* ... */ }
}Rules:
- Compare Unity objects with
== null,!= nullorif (obj). Never use?.,??,??=oris nullon aUnityEngine.Object(Rider and the Unity analyzers warn about it). - Plain C# classes (not derived from
UnityEngine.Object) behave normally;?.is fine on them. - Interfaces hide the overload:
IDamageable d = enemyComponent; d == nulluses the normal reference comparison. Cast back (d as Objectthen== null) or keep a component-typed reference. - Fake null also explains the Inspector: an unassigned serialized field in the editor is often a fake-null placeholder object, so
== nullis true butis nullis false.
Destroyed but still in your list
Destroy is deferred to the end of the frame, and your lists don't update themselves. A common bug is a List<Enemy> that still contains destroyed enemies:
// Remove destroyed entries (uses the overloaded ==):
enemies.RemoveAll(e => e == null);Better: have each enemy remove itself in OnDestroy, or raise an event the owner listens to. See C# Events & UnityEvents.
Note: The
==overload costs a native call. In very hot loops (thousands of checks per frame), keep your ownbool isAliveflag or compare against a cached state instead.
Test yourself
enemy was destroyed last frame. What does enemy?.transform do?
- Returns null safely
- Calls
.transformon the destroyed object and throws MissingReferenceException - Returns the last position
- Doesn't compile
Which check correctly detects a destroyed Unity object?
obj is nullobj == nullReferenceEquals(obj, null)obj ?? true
Why can a variable still reference a destroyed GameObject?
- Destroy is only a suggestion
- Destroy frees the native object; the managed C# wrapper stays until no references remain
- Unity copies objects on Destroy
- GameObjects are structs