References in the Inspector
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 43 of 85.
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
MediumSend each guard to the post its Inspector names.
- Add the field
public Transform post;. Guard1's slot holds Post1; Guard2's is empty. - In
Update(), whenpost == null,return;so a guard with no post stays put. - Then move with
Vector3.MoveTowards(transform.position, post.position, speed * Time.deltaTime).
Press Play: Guard1 walks to its post and Guard2 waits. 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.
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground