References in the Inspector
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 29 of 67.
A field can hold another object. Give it a type such as Transform or GameObject, and the Inspector shows an empty slot that you fill by dragging an object from the Hierarchy onto it. This camera script follows whatever object was dragged into player, staying 3 units above it and 6 behind:
public Transform player;
void Update()
{
transform.position = player.position + new Vector3(0, 3, -6);
}A slot left empty shows None, and the first line that uses it throws, on every frame: UnassignedReferenceException: The variable player of CameraFollow has not been assigned. The next line of the message says what to do: You probably need to assign the player variable of the CameraFollow script in the inspector. It names the field and the script, so you know which slot to fill.
Some scripts should work with the slot empty too. Unity makes an empty slot compare equal to null, so such a script checks before using it. With if (player != null) around the line in Update(), a camera with no player stays where it is instead of throwing.
Challenge
MediumEach guard walks to its own post. In the scene, Guard1's Inspector puts the Post1 object in a field named post. Guard2's post is not built yet, so its post slot is empty.
- Give the Guard script a
Transformfield namedpost. - A guard walks to its post's position at
speedunits per second and stops on it, even if the post is moved later. - A guard whose post slot is empty stays where it is, without an error.
Press Play, select each guard in the Hierarchy to see its Post slot, then Check.
Try it yourself
using UnityEngine;
public class Guard : MonoBehaviour
{
// post: the Transform this guard walks to, set in the Inspector
public float speed = 2f;
void Update()
{
// Walk to the post at speed. A guard with an empty post slot stays put.
}
}
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 Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch