Bird
Raised Fist0
Unityframework~15 mins

Variables and serialization in Unity - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of serialization in Unity?
easy
A. To convert data into a format that can be saved or sent
B. To create new game objects during runtime
C. To increase the speed of the game
D. To change the color of game objects

Solution

  1. Step 1: Recall the definition of serialization

    Serialization means converting data into a format that can be saved or sent.
  2. Step 2: Match Unity's use of serialization

    Unity uses serialization to save game data or send it over networks.
  3. Final Answer:

    To convert data into a format that can be saved or sent -> Option A
  4. Quick Check:

    Serialization = convert data for saving/sending [OK]
Hint: Serialization means saving or sending data format [OK]
Common Mistakes:
  • Confusing serialization with creating objects
  • Thinking serialization changes game speed
  • Mixing serialization with visual changes
2. Which of the following is the correct way to declare a public integer variable in a Unity C# script?
easy
A. int score public;
B. int public score;
C. public int score;
D. public integer score;

Solution

  1. Step 1: Recall C# variable declaration syntax

    In C#, access modifier comes first, then type, then variable name.
  2. Step 2: Check each option

    public int score; ('public int score;') follows correct order. Options A, B, C have wrong order or wrong type keyword.
  3. Final Answer:

    public int score; -> Option C
  4. Quick Check:

    Access modifier + type + name = correct declaration [OK]
Hint: Access modifier before type before name in C# [OK]
Common Mistakes:
  • Putting 'public' after variable name
  • Using 'integer' instead of 'int'
  • Incorrect order of keywords
3. What will be the output of this Unity C# code?
using UnityEngine;

public class PlayerData {
    public string playerName = "Alex";
    public int level = 5;
}

public class Test : MonoBehaviour {
    void Start() {
        PlayerData data = new PlayerData();
        string json = JsonUtility.ToJson(data);
        Debug.Log(json);
    }
}
medium
A. Error: JsonUtility.ToJson requires MonoBehaviour
B. {"playerName":Alex,"level":5}
C. {"playerName":"Alex",level:5}
D. {"playerName":"Alex","level":5}

Solution

  1. Step 1: Understand JsonUtility.ToJson output format

    JsonUtility converts object fields to JSON string with keys and values in quotes where needed.
  2. Step 2: Check the JSON string format

    Strings have quotes, numbers do not. {"playerName":"Alex","level":5} matches correct JSON format with quotes around "Alex" and keys.
  3. Final Answer:

    {"playerName":"Alex","level":5} -> Option D
  4. Quick Check:

    JsonUtility outputs valid JSON string [OK]
Hint: JsonUtility outputs JSON with quotes around strings [OK]
Common Mistakes:
  • Missing quotes around string values
  • Using invalid JSON syntax
  • Thinking JsonUtility needs MonoBehaviour object
4. Identify the error in this Unity C# code snippet:
using UnityEngine;

public class Player {
    public int score;
}

public class Game : MonoBehaviour {
    void Start() {
        Player player = new Player();
        string json = JsonUtility.ToJson(player);
        Debug.Log(json);
    }
}
medium
A. No error; code will output {"score":0}
B. Player class must inherit from MonoBehaviour to serialize
C. JsonUtility.ToJson requires static method call
D. score variable must be private to serialize

Solution

  1. Step 1: Check if Player class can be serialized

    JsonUtility can serialize plain classes with public fields, no need to inherit MonoBehaviour.
  2. Step 2: Check output of JsonUtility.ToJson

    Player's score defaults to 0, so JSON string will be {"score":0}.
  3. Final Answer:

    No error; code will output {"score":0} -> Option A
  4. Quick Check:

    Plain class with public fields serializes fine [OK]
Hint: Public fields in plain classes serialize without MonoBehaviour [OK]
Common Mistakes:
  • Thinking class must inherit MonoBehaviour to serialize
  • Assuming private fields serialize by default
  • Believing JsonUtility requires static context
5. You want to save player settings including volume (float), username (string), and isFullScreen (bool) using Unity's JsonUtility. Which class definition correctly supports serialization of these variables?
hard
A. public class Settings { private float volume; private string username; private bool isFullScreen; }
B. public class Settings { [SerializeField] private float volume; [SerializeField] private string username; [SerializeField] private bool isFullScreen; }
C. public class Settings { protected float volume; protected string username; protected bool isFullScreen; }
D. public class Settings { public float volume { get; set; } public string username { get; set; } public bool isFullScreen { get; set; } }

Solution

  1. Step 1: Understand JsonUtility serialization rules

    JsonUtility serializes public fields or private fields marked with [SerializeField] attribute.
  2. Step 2: Evaluate each class definition

    public class Settings { protected float volume; protected string username; protected bool isFullScreen; } uses protected fields, which do not serialize. public class Settings { private float volume; private string username; private bool isFullScreen; } uses private fields without [SerializeField], so no serialization. public class Settings { [SerializeField] private float volume; [SerializeField] private string username; [SerializeField] private bool isFullScreen; } uses private fields with [SerializeField], which works. public class Settings { public float volume { get; set; } public string username { get; set; } public bool isFullScreen { get; set; } } uses properties, which JsonUtility does not serialize.
  3. Step 3: Choose best practice

    Using private fields with [SerializeField] is recommended for encapsulation and serialization.
  4. Final Answer:

    public class Settings { [SerializeField] private float volume; [SerializeField] private string username; [SerializeField] private bool isFullScreen; } -> Option B
  5. Quick Check:

    Private fields + [SerializeField] serialize correctly [OK]
Hint: Use [SerializeField] for private variables to serialize [OK]
Common Mistakes:
  • Assuming private fields serialize without attribute
  • Using properties instead of fields for serialization
  • Ignoring encapsulation best practices
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard