TExcelTAD
Home › Unity with C# › Serialized Fields & the Inspector

Serialized Fields & the Inspector

Unity saves scenes, prefabs and ScriptableObjects by serializing the fields of your components into YAML text. Whatever Unity serializes also appears in the Inspector, where designers can tune it without touching code. Knowing the rules saves you from values that silently reset to zero.

What gets serialized

A field is serialized when it is:

  • public, or private/protected with [SerializeField];
  • not static, const or readonly, and not marked [NonSerialized];
  • of a serializable type: primitives, string, enums, Unity types (Vector3, Color, AnimationCurve, LayerMask…), references to UnityEngine.Objects (assets, components, GameObjects), arrays and List<T> of these, and your own [System.Serializable] classes and structs.

Not serialized: properties ({ get; set; }), Dictionary, interfaces, multi-dimensional arrays and nested lists (List<List<int>>). For polymorphic plain classes, use [SerializeReference].

csharp
using System;
using System.Collections.Generic;
using UnityEngine;

public class EnemyStats : MonoBehaviour
{
    [Header("Movement")]
    [SerializeField, Range(0f, 20f)] float speed = 4f;
    [SerializeField, Min(0f)] float turnRate = 180f;

    [Header("Combat")]
    [SerializeField] int maxHealth = 50;
    [SerializeField, Tooltip("Seconds between attacks")] float attackCooldown = 1.2f;
    [SerializeField] List<Drop> drops = new();

    // Read-only access for other scripts, editable only in the Inspector.
    public float Speed => speed;
    public int MaxHealth => maxHealth;

    // Auto-property that is still serialized (the backing field gets the attribute):
    [field: SerializeField] public string DisplayName { get; private set; } = "Grunt";
}

[Serializable]
public class Drop
{
    public string itemId;
    [Range(0f, 1f)] public float chance;
}

Prefer [SerializeField] private over public fields: the Inspector still shows them, but other scripts can't change them behind your back.

Note: the initializer (= 4f) is only the default for new components. Once a component exists in a scene, the scene's saved value wins. Changing the initializer in code does not change existing objects. This surprises everyone once.

Renames lose data

Serialized data is stored by field name. Rename maxHealth to maxHp and Unity finds no data for maxHp: every enemy in every scene silently falls back to the default. The fix is [FormerlySerializedAs] from UnityEngine.Serialization. The model below implements both behaviours with C# reflection and its own copies of the attributes:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Reflection;

// The YAML Unity saved for one enemy, back when the field was called "maxHealth".
var savedYaml = new Dictionary<string, string> { ["speed"] = "7.5", ["maxHealth"] = "120" };

Console.WriteLine("renamed without attribute: " + Load<EnemyV2>(savedYaml));
Console.WriteLine("renamed with attribute:    " + Load<EnemyV3>(savedYaml));

static T Load<T>(Dictionary<string, string> yaml) where T : new()
{
    var obj = new T();
    foreach (var f in typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    {
        bool serialized = f.IsPublic || f.GetCustomAttribute<SerializeField>() != null;
        if (!serialized) continue;
        var names = new List<string> { f.Name };
        foreach (var old in f.GetCustomAttributes<FormerlySerializedAs>()) names.Add(old.OldName);
        foreach (var name in names)
            if (yaml.TryGetValue(name, out var text))
            {
                f.SetValue(obj, Convert.ChangeType(text, f.FieldType, System.Globalization.CultureInfo.InvariantCulture));
                break;
            }
    }
    return obj;
}

[AttributeUsage(AttributeTargets.Field)] class SerializeField : Attribute { }
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
class FormerlySerializedAs : Attribute { public string OldName; public FormerlySerializedAs(string n) => OldName = n; }

class EnemyV2
{
    [SerializeField] float speed = 4f;
    [SerializeField] int maxHp = 50;                       // renamed: data for "maxHealth" is ignored
    public override string ToString() => 
quot;speed={speed} maxHp={maxHp}"; } class EnemyV3 { [SerializeField] float speed = 4f; [SerializeField, FormerlySerializedAs("maxHealth")] int maxHp = 50; public override string ToString() =>
quot;speed={speed} maxHp={maxHp}"; }
renamed without attribute: speed=7.5 maxHp=50
renamed with attribute:    speed=7.5 maxHp=120

In Unity:

csharp
using UnityEngine;
using UnityEngine.Serialization;

public class EnemyStats : MonoBehaviour
{
    [FormerlySerializedAs("maxHealth")]
    [SerializeField] int maxHp = 50;
}

Keep the attribute until every scene, prefab and asset has been re-saved with the new name. Rider can add it automatically when you rename a serialized field.

Validating values in the editor

OnValidate runs in the editor whenever a value changes in the Inspector (and on load). Use it to clamp or derive values, never for gameplay:

csharp
void OnValidate()
{
    if (attackCooldown < 0.1f) attackCooldown = 0.1f;
    if (drops.Count > 8) Debug.LogWarning(
quot;{name}: more than 8 drops", this); }

The second argument of Debug.Log* is a context object: clicking the log line in the Console highlights that object.

Test yourself

Which of these fields does Unity serialize?

  1. public static int count;
  2. [SerializeField] private float speed;
  3. public float Speed { get; set; }
  4. private Dictionary<string, int> stock;

You change [SerializeField] int lives = 3; to = 5; in code. What do existing objects in your scenes show?

  1. 5
  2. Their saved value (3, unless edited)
  3. 0
  4. A compile error

You rename a serialized field. How do you keep the data already saved in scenes?

  1. [NonSerialized]
  2. [FormerlySerializedAs("oldName")]
  3. [HideInInspector]
  4. Delete the Library folder