Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท C# Scripting

Inspector Fields and Attributes

Expose script variables in the Unity Inspector with public and SerializeField, organize them with Header, Range, Tooltip and Space attributes, and understand serialization rules, with runnable stand-ins.

One of Unity's best ideas is that you can tweak a game without touching code. Make a variable visible in the Inspector and designers (or you, in Play Mode) can change speed, jump height or damage with a slider. This lesson shows how a field becomes visible, the attributes that make the Inspector friendlier, and the rules of serialization, the process that stores those values in scenes and prefabs.

The Unity scripts are read-only. The stand-ins model serialization with plain C# so the rules become concrete.

Public fields and [SerializeField]

A field appears in the Inspector when Unity can serialize it. Two ways to get there:

C#
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed = 3f;                // visible; accessible from other scripts
    [SerializeField] int maxHealth = 20;    // visible; private to other scripts
    int currentHealth;                      // not visible: private, no attribute

    void Awake() { currentHealth = maxHealth; }
}

The recommended style is [SerializeField] private for values you tweak in the editor but should not be changed from other scripts: it keeps encapsulation. Make a field public only when other scripts must read or write it. To expose a value for reading only, add a property: public int MaxHealth => maxHealth;.

The value you type in the Inspector wins over the initializer in code (= 3f). The initializer is only the default for newly added components. This surprises many beginners: change the code default later and existing objects keep their saved value. Use Reset in the component's three-dot menu to apply the new default.

What Unity can serialize

Unity serializes:

  • primitives: int, float, bool, string, char, enums,
  • Unity structs: Vector2, Vector3, Quaternion, Color, Rect, AnimationCurve, LayerMask,
  • references to objects: GameObject, Transform, any Component, any asset type (Material, AudioClip, Sprite),
  • arrays and List<T> of the types above,
  • your own classes and structs marked [System.Serializable].

It does not serialize: properties (unless you use [field: SerializeField]), dictionaries, static fields, const/readonly fields, and multidimensional arrays. Interfaces and abstract types need [SerializeReference].

C#
using System;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class Drop
{
    public GameObject prefab;
    [Range(0f, 1f)] public float chance = 0.25f;
}

public class LootTable : MonoBehaviour
{
    public List<Drop> drops = new List<Drop>();   // appears as an expandable list
    [field: SerializeField] public string DisplayName { get; private set; }   // auto-property backing field
}

Attributes that organize the Inspector

Attribute Effect
[Header("Movement")] Bold label above a group of fields
[Space(10)] Vertical gap
[Tooltip("Units per second")] Hover text
[Range(0, 10)] Slider (works on int and float)
[Min(0)] Prevents values below a minimum
[TextArea(3, 6)] Multi-line text box
[HideInInspector] Public but hidden
[NonSerialized] Not serialized and not shown
[ColorUsage(true, true)] HDR color picker
[ContextMenu("Reset Health")] Adds a right-click menu item that calls the method
[RequireComponent(typeof(T))] Dependency on another component
[DisallowMultipleComponent] Only one of this script per object
[ExecuteAlways] Run lifecycle methods in Edit Mode too

A well-organized script:

C#
using UnityEngine;

public class PlayerStats : MonoBehaviour
{
    [Header("Movement")]
    [Tooltip("Walking speed in units per second")]
    [SerializeField, Range(0f, 15f)] float walkSpeed = 5f;
    [SerializeField, Min(0f)] float jumpHeight = 1.5f;

    [Space(10)]
    [Header("Combat")]
    [SerializeField] int maxHealth = 100;
    [SerializeField, TextArea(2, 4)] string description;

    [ContextMenu("Print stats")]
    void PrintStats() => Debug.Log($"{walkSpeed} / {jumpHeight} / {maxHealth}");
}

Validating values: OnValidate

OnValidate runs in the editor whenever a value changes in the Inspector (and when the script loads). Use it to clamp or correct values and to keep dependent fields in step:

C#
void OnValidate()
{
    maxHealth = Mathf.Max(1, maxHealth);
    walkSpeed = Mathf.Clamp(walkSpeed, 0f, 15f);
}

Do not call Destroy or create objects there; keep it to simple value fixing.

Referencing objects in the Inspector

The most powerful use of serialization is references. Instead of searching for an object in code, drag it into a field:

C#
using UnityEngine;

public class Turret : MonoBehaviour
{
    [SerializeField] Transform target;            // drag any object here
    [SerializeField] GameObject bulletPrefab;     // drag a prefab here
    [SerializeField] AudioClip fireSound;         // drag an audio file here

    void Update()
    {
        if (target != null)
            transform.LookAt(target);
    }
}

Dragging a field's reference is safe against renaming (Unity stores an ID, not a name), faster than Find, and visible to everyone who opens the scene. If a reference stays empty, the Inspector shows None (Transform); accessing it gives a NullReferenceException. Check in Awake and log a clear message:

C#
void Awake()
{
    if (target == null) Debug.LogError("Turret has no target assigned", this);
}

Modeling serialization in plain C#

Unity stores serialized values as text (YAML) in scene and prefab files. This stand-in uses System.Text.Json to do something similar: it saves the public fields of an object and loads them back, and it shows that a field the serializer ignores is not saved.

C# Saving and loading fields (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

That is the Inspector rule in action: serialized fields are remembered by the scene, the others restart from their defaults when the scene loads.

Clamping like Range and OnValidate (stand-in)

Here is the logic of [Range] and OnValidate in a runnable form: values entered by a "designer" are corrected before they reach the game.

C# Validating inspector values (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Tips and pitfalls

  • Renaming a serialized field loses its saved value; use [FormerlySerializedAs("oldName")] to keep it.
  • Do not initialize a public List<T> in a way that overrides saved data at run time; Unity creates it for you.
  • Changes made to a ScriptableObject or prefab asset in Play Mode persist after you stop (they are assets); scene object changes do not.
  • Use the Debug inspector mode to see private non-serialized fields while testing.
  • Keep an eye on public fields: any script can change them. Prefer [SerializeField] private plus a read-only property.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of [SerializeField] private over public?

    You keep the Inspector convenience and encapsulation.
  2. 2. You change a field's default value in code from 3f to 5f, but existing objects still show 3. Why?

    The saved scene or prefab value wins. Use Reset on the component to apply the new default.
  3. 3. Which of these is NOT serialized by Unity by default?

    Dictionaries are not serialized by Unity.
  4. 4. Which attribute draws a slider?

    Range shows a slider for int and float fields.

Summary

  • Public fields and [SerializeField] private fields appear in the Inspector; the saved value overrides the code default.
  • Unity serializes primitives, common Unity types, references, arrays/lists and [Serializable] classes, but not dictionaries or properties.
  • Use Header, Tooltip, Range, Min, Space, TextArea and OnValidate to make inspectors safe and readable.
  • Dragging references in the Inspector beats searching by name in code.

Next: Time and Frame-Independent Movement