0
0
Unityframework~15 mins

Variables and serialization in Unity - Deep Dive

Choose your learning style9 modes available
Overview - Variables and serialization
What is it?
Variables in Unity are containers that store data like numbers, text, or objects. Serialization is the process of converting these variables into a format that Unity can save and load, such as when saving a game or showing values in the Inspector. This lets Unity remember the state of your game objects between sessions or during editing. Without serialization, Unity wouldn't be able to keep track of changes made in the editor or save game progress.
Why it matters
Serialization allows Unity to save and load game data, making games feel continuous and interactive. It also lets developers tweak variables in the editor and see changes immediately, speeding up development. Without serialization, every time you stopped playing or closed the editor, all your changes and progress would be lost, making game development and play impossible to manage.
Where it fits
Before learning this, you should understand basic programming concepts like variables and data types. After this, you can explore Unity's scripting lifecycle, custom editors, and saving/loading game states. Serialization connects basic coding with how Unity manages data behind the scenes.
Mental Model
Core Idea
Serialization is like packing variables into a suitcase so Unity can save, transport, and unpack them later exactly as they were.
Think of it like...
Imagine you want to move your clothes to a new house. You pack them neatly into boxes (serialization), label them, and when you arrive, you unpack the boxes to get your clothes back in the same order (deserialization). Variables are the clothes, and serialization is the packing process.
Variables ──▶ [Serialization Process] ──▶ Saved Data
   ▲                                         ▼
   │                                         │
   └────────────── Deserialization ──────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Variables in Unity
🤔
Concept: Learn what variables are and how Unity uses them to store data.
Variables hold information like numbers, text, or references to objects. In Unity, you declare variables inside scripts to control game behavior. For example, an integer variable can store a player's score, and a string can store a player's name.
Result
You can store and change data in your game scripts to control how your game behaves.
Knowing variables is essential because they are the building blocks for storing and manipulating game data.
2
FoundationWhat is Serialization in Unity?
🤔
Concept: Serialization converts variables into a format Unity can save and load.
Unity needs to save the state of variables so it can remember them between play sessions or when editing. Serialization turns variables into data Unity can store in files or show in the Inspector. Without serialization, Unity wouldn't keep track of your variable values.
Result
Unity can save and restore variable values, making game progress and editor changes persistent.
Understanding serialization explains how Unity preserves your game data and editor settings.
3
IntermediateUnity's Serialization Rules
🤔Before reading on: do you think all variables in Unity scripts are saved automatically? Commit to yes or no.
Concept: Not all variables are serialized by default; Unity follows specific rules to decide what to save.
Unity serializes public fields and private fields marked with [SerializeField]. It supports basic types (int, float, string), Unity types (Vector3, Color), and custom classes marked as serializable. Static variables and properties are not serialized. Understanding these rules helps control what data Unity saves.
Result
You can control which variables Unity saves and shows in the Inspector by using access modifiers and attributes.
Knowing serialization rules prevents confusion about why some variables appear in the Inspector and others don't.
4
IntermediateUsing [SerializeField] and Access Modifiers
🤔Before reading on: do you think private variables can be shown in the Inspector without any special attribute? Commit to yes or no.
Concept: The [SerializeField] attribute lets private variables be serialized and visible in the Inspector.
By default, only public variables are serialized and shown in the Inspector. If you want to keep a variable private but still save and edit it in the Inspector, add [SerializeField] before its declaration. This keeps your code encapsulated but editable in Unity's editor.
Result
Private variables can be saved and edited in the Inspector, improving code safety and flexibility.
Understanding this attribute helps balance good coding practices with Unity's serialization system.
5
IntermediateSerialization of Custom Classes and Structs
🤔Before reading on: do you think Unity can serialize any custom class automatically? Commit to yes or no.
Concept: Unity can serialize custom classes only if they are marked with [System.Serializable] and follow serialization rules.
To serialize a custom class, add [System.Serializable] above its definition. The class must contain only serializable fields. Unity cannot serialize properties or complex types like dictionaries by default. This lets you organize data neatly and still have it saved and editable.
Result
Custom data structures can be saved and edited in the Inspector, making complex data management easier.
Knowing how to serialize custom classes unlocks powerful ways to organize and save game data.
6
AdvancedLimitations and Gotchas of Unity Serialization
🤔Before reading on: do you think Unity can serialize all C# types and data structures? Commit to yes or no.
Concept: Unity's serialization system has limits; some types and structures are not supported or behave unexpectedly.
Unity cannot serialize properties, static fields, events, or certain collections like dictionaries and multi-dimensional arrays. Also, references to objects outside the scene or assets may not serialize as expected. Understanding these limits helps avoid bugs and data loss.
Result
You can design your data to fit Unity's serialization system and avoid common pitfalls.
Knowing serialization limits prevents frustrating bugs and data loss in your projects.
7
ExpertCustom Serialization and ISerializationCallbackReceiver
🤔Before reading on: do you think Unity allows you to customize how your data is saved and loaded? Commit to yes or no.
Concept: Unity provides interfaces and methods to customize serialization beyond default behavior.
By implementing ISerializationCallbackReceiver, you can run code before serialization and after deserialization. This lets you prepare data for saving or reconstruct it after loading. This is useful for complex data or when you need to maintain references or caches that Unity can't serialize automatically.
Result
You gain full control over how your data is saved and restored, enabling advanced data management.
Understanding custom serialization unlocks expert-level control and solves complex data challenges in Unity.
Under the Hood
Unity's serialization system scans scripts for fields that meet its rules (public or marked with [SerializeField]). It converts these fields into a serialized format stored in scene files, prefabs, or asset files. When loading, Unity reads this data and reconstructs the variables in memory. This process happens automatically during editing and runtime, allowing Unity to keep track of variable states.
Why designed this way?
Unity's serialization was designed to balance ease of use, performance, and editor integration. It uses simple rules to avoid complex reflection overhead and to keep the Inspector responsive. The system focuses on common data types and patterns to cover most use cases, while allowing customization for advanced needs. Alternatives like full C# serialization were avoided due to complexity and performance costs.
┌─────────────┐       ┌─────────────────────┐       ┌───────────────┐
│ Script Code │──────▶│ Serialization Rules │──────▶│ Serialized Data│
└─────────────┘       └─────────────────────┘       └───────────────┘
       ▲                                                    │
       │                                                    ▼
┌─────────────┐       ┌─────────────────────┐       ┌───────────────┐
│ Runtime Use │◀──────│ Deserialization Code │◀──────│ Saved Data    │
└─────────────┘       └─────────────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think private variables are always saved by Unity? Commit to yes or no.
Common Belief:Private variables are saved and shown in the Inspector just like public ones.
Tap to reveal reality
Reality:Unity only serializes private variables if they have the [SerializeField] attribute; otherwise, they are ignored.
Why it matters:Assuming private variables are saved can cause data loss and confusion when values reset unexpectedly.
Quick: Do you think Unity can serialize any C# object automatically? Commit to yes or no.
Common Belief:Unity can serialize all C# objects and data structures without extra work.
Tap to reveal reality
Reality:Unity only serializes supported types and classes marked with [System.Serializable]; many C# features like properties and dictionaries are not serialized.
Why it matters:Expecting full serialization leads to bugs where data is missing or not saved, causing runtime errors or lost progress.
Quick: Do you think static variables are saved by Unity's serialization? Commit to yes or no.
Common Belief:Static variables are saved and restored like instance variables.
Tap to reveal reality
Reality:Static variables are never serialized by Unity because they belong to the class, not instances.
Why it matters:Relying on static variables for saved data causes unexpected resets and inconsistent game states.
Quick: Do you think Unity serialization preserves object references perfectly? Commit to yes or no.
Common Belief:Unity serialization always keeps references between objects intact after loading.
Tap to reveal reality
Reality:Unity can serialize references within the same scene or prefab but may lose references to objects outside or dynamically created at runtime.
Why it matters:Misunderstanding this causes null references and bugs when objects lose their connections after loading.
Expert Zone
1
Unity's serialization system does not serialize properties, only fields, which can surprise developers expecting full C# behavior.
2
Renaming or removing serialized fields can break backward compatibility with saved data.
3
Unity uses a custom serialization format optimized for speed and editor integration, not standard C# binary or JSON serialization.
When NOT to use
Unity's built-in serialization is not suitable for complex data structures like dictionaries, polymorphic types, or large datasets. In these cases, use custom serialization methods like JSON, XML, or binary serialization with external libraries.
Production Patterns
In production, developers use [SerializeField] to expose private variables safely, implement ISerializationCallbackReceiver for complex data handling, and combine Unity serialization with custom save systems for player progress and settings.
Connections
Data Persistence
Serialization is a core technique enabling data persistence in software systems.
Understanding Unity serialization helps grasp how games save progress, similar to how databases or files store data in other applications.
Object-Oriented Programming
Serialization interacts closely with class design and encapsulation principles in OOP.
Knowing serialization rules clarifies how access modifiers and attributes affect data visibility and storage in object-oriented code.
Packing and Unpacking in Logistics
Serialization is analogous to packing items for transport and unpacking them later.
Recognizing this connection helps understand the importance of format, order, and completeness in saving and restoring data.
Common Pitfalls
#1Expecting private variables to be saved without attributes
Wrong approach:private int playerHealth = 100;
Correct approach:[SerializeField] private int playerHealth = 100;
Root cause:Misunderstanding that Unity only serializes public fields or private fields marked with [SerializeField].
#2Trying to serialize unsupported types like dictionaries
Wrong approach:public Dictionary inventory = new Dictionary();
Correct approach:Use a serializable list of key-value pairs or custom serialization methods instead.
Root cause:Assuming Unity's serialization supports all C# types without restrictions.
#3Relying on static variables for saved data
Wrong approach:public static int highScore = 0;
Correct approach:Use instance variables with serialization or external save systems.
Root cause:Not realizing static variables are not serialized because they belong to the class, not instances.
Key Takeaways
Variables store data in Unity scripts, and serialization saves this data so it persists between sessions.
Unity only serializes public fields and private fields marked with [SerializeField], following specific rules.
Custom classes must be marked with [System.Serializable] to be serialized by Unity.
Unity's serialization has limits; it does not support all C# types or static variables.
Advanced control over serialization is possible with interfaces like ISerializationCallbackReceiver.