Course contentsShow
← Unity Game Development
Lesson 285 of 8284. Prefabs and Data ManagementFree lesson

Understanding Unity Serialization Rules and Constraints

Learners will identify which field types and data structures are compatible with Unity's serializer to ensure variables persist across sessions.

In this lesson, you will learn which C# variable types Unity’s serialization system can "see" and save to disk, ensuring your data persists across scene loads and inspector sessions.

Why Serialization Matters

Serialization is the process where Unity converts your script’s variables into a format it can store in a scene file, a Prefab, or a ScriptableObject. If a field isn't serialized, Unity will effectively "forget" it the moment you stop the game or close the editor.

The Rules of Compatibility

To ensure your variables show up in the Inspector and persist, they must adhere to specific rules:

  1. Public or [SerializeField]: Unity serializes all public fields. If you want to keep a field private while still saving it, you must add the [SerializeField] attribute above it.
  2. Basic Types: Unity supports primitive types like int, float, string, bool, and Vector3.
  3. Unity Objects: Fields that inherit from UnityEngine.Object (like GameObject, Transform, or your own MonoBehaviour scripts) are serializable.
  4. Custom Classes/Structs: You can serialize your own classes or structs, but you must mark them with the [System.Serializable] attribute.

What Doesn’t Work?

Unity’s serializer is not a general-purpose C# serializer; it has limits. It cannot serialize:

  • static fields (these belong to the class, not the instance).
  • readonly fields.
  • C# Properties (the ones with { get; set; }).
  • Complex collections like nested dictionaries (though you can use tricks with two lists).
using UnityEngine;

public class SerializationExample : MonoBehaviour
{
    public int health; // Will be serialized
    
    [SerializeField] 
    private float speed; // Private, but will be serialized
    
    [System.Serializable]
    public struct PlayerStats // Custom struct must be marked serializable
    {
        public int level;
        public string playerName;
    }

    public PlayerStats stats; 
}

If you ever find that a value in your Inspector resets to default when you press Play or switch scenes, it is almost always because the data structure you are using is incompatible with these serialization rules. Always check if you’ve marked your custom types with [System.Serializable] and ensure you aren't trying to serialize unsupported data like complex C# dictionaries.

Key Takeaway: For data to persist in the Unity Inspector and save to disk, variables must be public or marked [SerializeField], and any custom classes or structs must explicitly use the [System.Serializable] attribute.