Inspector Fields
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 14 of 85.
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
EasyMake the elevator rise at the speed its Inspector sets.
- In
Update(), replace the2with the field:lift * Time.deltaTime. - Leave
public float lift = 2f;as it is: the Inspector setsliftto 6.
Press Play: the elevator rises 6 units a second. Then 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);
}
}
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