SerializeField
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 15 of 85.
A public field does two jobs at once: it shows in the Inspector, and every other script can read and change it. Often you want only the first. A private field (the default in C#) can be changed by its own class only, so no other script can break it, but Unity does not show it in the Inspector.
[SerializeField] asks Unity to save and show a private field anyway. This turret's range is set per turret in the Inspector, and no other script can touch it:
[SerializeField] private float range = 5f;
void Start()
{
Debug.Log("Range: " + range);
}This is how most Unity code keeps its settings: private, with [SerializeField]. Watch out for the reverse: make a field private and forget the attribute, and Unity silently drops the value saved in the scene. The field falls back to the number in the code, with no error to tell you.
Challenge
EasyHide the lamp's height from other scripts but keep it in the Inspector.
- Change the field to
[SerializeField] private float height = 1f;. - Keep
Start()as it is: the Inspector setsheightto 4.
Press Play: the lamp still hangs at a height of 4. Then Check.
Try it yourself
using UnityEngine;
public class LampHeight : MonoBehaviour
{
public float height = 1f;
void Start()
{
transform.position = new Vector3(0, height, 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