Unity's Null
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 46 of 67.
A Unity object has two halves: the C# object your script holds, and the engine object behind it. Destroy(obj) removes the engine half at the end of the frame, but your variable still points at the C# half, so in plain C# terms it is not null. Unity overrides == to cover this: once the object is destroyed, obj == null is true, and so is the short test !obj. This is Unity's fake null.
?., ?? and is null do not use that ==. They test the C# reference, which still exists, so they let the call through, and touching the destroyed object throws MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it. This label shows the name of the race leader, who can be knocked out (destroyed):
[SerializeField] private Transform leader;
void Update()
{
// throws once the leader is destroyed: string shown = leader?.name ?? "nobody";
string shown = leader != null ? leader.name : "nobody";
Debug.Log("Leader: " + shown);
}For anything that comes from UnityEngine.Object (GameObjects, components, your scripts), test with == null, != null or if (obj), and keep ?. and ?? for plain C# objects such as strings. Also remember that Destroy waits for the end of the frame: until then, the object is still alive and == null is false.
Challenge
MediumThe drone chases its target, and the target is destroyed 2 seconds into the game. From then on the Console fills with MissingReferenceException, because target?.position does not notice that the target is gone.
Fix Update() with Unity's own null test: while the target exists, the drone flies toward it at speed; once it is destroyed, the drone stays where it is, with no errors.
Press Play and watch the Console, fix the script, then Check.
Try it yourself
using UnityEngine;
public class Chaser : MonoBehaviour
{
[SerializeField] private Transform target;
[SerializeField] private float speed = 2f;
void Start()
{
Destroy(target.gameObject, 2f); // the target is destroyed after 2 seconds
}
void Update()
{
Vector3 goal = target?.position ?? transform.position;
transform.position = Vector3.MoveTowards(transform.position, goal, speed * Time.deltaTime);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon