Menu
CoddyTech

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 icon

Challenge

Medium

Send each guard to the post its Inspector names.

  1. Add the field public Transform post;. Guard1's slot holds Post1; Guard2's is empty.
  2. In Update(), when post == null, return; so a guard with no post stays put.
  3. 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

Practice on your own: Unity playground