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:
- Public or
[SerializeField]: Unity serializes allpublicfields. If you want to keep a field private while still saving it, you must add the[SerializeField]attribute above it. - Basic Types: Unity supports primitive types like
int,float,string,bool, andVector3. - Unity Objects: Fields that inherit from
UnityEngine.Object(likeGameObject,Transform, or your ownMonoBehaviourscripts) are serializable. - 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:
staticfields (these belong to the class, not the instance).readonlyfields.- 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.