Menu
CoddyTech

SerializeField

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 8 of 67.

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

The lamp's height is public, so any script could move it. Make height private while keeping it in the Inspector, which sets it to 4. The lamp must still hang at the Inspector's height.

Press Play and look at the lamp's height, then Check.

Try it yourself

using UnityEngine;

public class LampHeight : MonoBehaviour
{
    public float height = 1f;

    void Start()
    {
        transform.position = new Vector3(0, height, 0);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics