Inspector Fields
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 7 of 67.
A public field of a script shows up in the Inspector, under the script's name, where anyone building the scene can change it without touching the code. That is how one Spinner script turns a fan fast and a windmill slowly: the same code, a different number on each object.
The number in the code is only the starting value Unity uses when the script is first added. After that, the value saved in the scene wins. Here the code says 3, but this rocket's Inspector says 8, so the rocket climbs 8 units per second:
public float speed = 3f; // the Inspector shows 8 on this rocket
void Update()
{
transform.position += new Vector3(0, speed * Time.deltaTime, 0);
}Changing = 3f in the code does not change a rocket already in the scene. This trips up most Unity beginners at least once: when a number seems to be ignored, look at the Inspector. Select an object in the Hierarchy to see its fields.
Challenge
EasyThe elevator's Inspector sets lift to 6, but the script ignores the field and always rises 2 units per second. Change Update() so the elevator rises at lift units per second, whatever the Inspector says.
Select the Elevator in the Hierarchy to see its lift, then Play and Check.
Try it yourself
using UnityEngine;
public class Elevator : MonoBehaviour
{
public float lift = 2f;
void Update()
{
transform.position += new Vector3(0, 2 * Time.deltaTime, 0);
}
}
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