Bird
Raised Fist0
Unityframework~10 mins

Variables and serialization in Unity - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Variables and serialization
Declare variable
↓
Assign value
↓
Serialize variable
↓
Save to file or memory
↓
Deserialize variable
↓
Use restored value
↓
End
This flow shows how a variable is declared, given a value, saved (serialized), then loaded back (deserialized) for use.
Execution Sample
Unity
using UnityEngine;

public class Example : MonoBehaviour {
    [SerializeField] private int score = 10;
}
This code declares a private variable 'score' with initial value 10 and marks it to be serialized by Unity.
Execution Table
StepActionVariableValueSerialization State
1Declare variable 'score'scoreundefinedNot serialized yet
2Assign initial valuescore10Not serialized yet
3Serialize variablescore10Serialized to Unity Editor and saved
4Save to file/memoryscore10Stored in scene or prefab data
5Deserialize variablescore10Loaded back from saved data
6Use variable in gamescore10Active in runtime
7End---
💡 Serialization completes when variable is saved and loaded back correctly.
Variable Tracker
VariableStartAfter AssignAfter SerializeAfter DeserializeFinal
scoreundefined10101010
Key Moments - 3 Insights
Why do we use [SerializeField] on a private variable?
Because private variables are hidden from Unity's Inspector by default, [SerializeField] tells Unity to save and show it anyway, as shown in step 3 of the execution_table.
Does serialization change the variable's value?
No, serialization saves the current value without changing it. The value remains 10 before and after serialization (see variable_tracker).
What happens if we don't serialize a variable?
Unity won't save its value between sessions, so it resets to default or code value on reload. This is why serialization is important (step 3 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'score' after step 2?
A0
Bundefined
C10
Dnull
💡 Hint
Check the 'Value' column at step 2 in the execution_table.
At which step does the variable 'score' get saved to file or memory?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look for the action mentioning saving to file or memory in the execution_table.
If we remove [SerializeField], what happens to the variable 'score' in Unity Inspector?
AIt becomes invisible and not serialized
BIt causes a compile error
CIt remains visible and serialized
DIt becomes public automatically
💡 Hint
Refer to the key_moments about [SerializeField] usage.
Concept Snapshot
Variables hold data in Unity scripts.
[SerializeField] makes private variables visible and saved.
Serialization saves variable values to disk or memory.
Deserialization restores saved values when loading.
Without serialization, values reset on reload.
Full Transcript
This lesson shows how variables in Unity scripts can be saved and loaded using serialization. We start by declaring a variable called 'score' and assign it the value 10. Using the [SerializeField] attribute, Unity knows to save this private variable's value. Serialization means saving the variable's current value to a file or memory so it can be restored later. When the game or editor reloads, Unity deserializes the variable, loading back the saved value. This way, the variable keeps its value between sessions. Without serialization, private variables would reset to default values and not keep changes made in the editor or during gameplay. The execution table traces each step from declaration, assignment, serialization, saving, deserialization, to usage. The variable tracker shows the value stays 10 throughout. Key moments clarify why [SerializeField] is needed and that serialization does not change the value. The quiz tests understanding of variable values at steps and the effect of serialization attributes.

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