TExcelTAD
Home › Unity with C# › Destroyed Objects & Fake Null

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.

csharp · try it yourself
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

csharp
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:

  1. Compare Unity objects with == null, != null or if (obj). Never use ?., ??, ??= or is null on a UnityEngine.Object (Rider and the Unity analyzers warn about it).
  2. Plain C# classes (not derived from UnityEngine.Object) behave normally; ?. is fine on them.
  3. Interfaces hide the overload: IDamageable d = enemyComponent; d == null uses the normal reference comparison. Cast back (d as Object then == null) or keep a component-typed reference.
  4. Fake null also explains the Inspector: an unassigned serialized field in the editor is often a fake-null placeholder object, so == null is true but is null is 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:

csharp
// 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 own bool isAlive flag or compare against a cached state instead.

Test yourself

enemy was destroyed last frame. What does enemy?.transform do?

  1. Returns null safely
  2. Calls .transform on the destroyed object and throws MissingReferenceException
  3. Returns the last position
  4. Doesn't compile

Which check correctly detects a destroyed Unity object?

  1. obj is null
  2. obj == null
  3. ReferenceEquals(obj, null)
  4. obj ?? true

Why can a variable still reference a destroyed GameObject?

  1. Destroy is only a suggestion
  2. Destroy frees the native object; the managed C# wrapper stays until no references remain
  3. Unity copies objects on Destroy
  4. GameObjects are structs