Menu
CoddyTech

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 icon

Challenge

Easy

Hide the lamp's height from other scripts but keep it in the Inspector.

  1. Change the field to [SerializeField] private float height = 1f;.
  2. Keep Start() as it is: the Inspector sets height to 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

Practice on your own: Unity playground