What if your game could remember everything automatically without you writing endless save code?
Why Variables and serialization in Unity? - Purpose & Use Cases
Imagine you are making a game in Unity and want to save the player's score and settings so they don't lose progress when they close the game.
You try to write all the data manually every time the player changes something, but it quickly becomes confusing and messy.
Manually saving and loading each piece of data is slow and easy to forget.
You might save the wrong value or miss some important information, causing bugs and lost progress.
It also makes your code long and hard to read.
Using variables and serialization in Unity lets you store data neatly and automatically save or load it as needed.
Serialization turns your variables into a format that Unity can save to a file or memory, so you don't have to write all the saving code yourself.
PlayerPrefs.SetInt("score", score); PlayerPrefs.SetString("playerName", name);
[System.Serializable] public class PlayerData { public int score; public string playerName; } // Use JsonUtility.ToJson to serialize and save to file or PlayerPrefs
You can easily save and load complex game data, making your game remember player progress and settings without extra hassle.
Think of a game where you collect coins and unlock levels. Serialization saves your coin count and unlocked levels so you can continue exactly where you left off.
Manual saving is slow and error-prone.
Serialization automates saving variables in Unity.
This keeps your game data safe and your code clean.
Practice
Solution
Step 1: Recall the definition of serialization
Serialization means converting data into a format that can be saved or sent.Step 2: Match Unity's use of serialization
Unity uses serialization to save game data or send it over networks.Final Answer:
To convert data into a format that can be saved or sent -> Option AQuick Check:
Serialization = convert data for saving/sending [OK]
- Confusing serialization with creating objects
- Thinking serialization changes game speed
- Mixing serialization with visual changes
Solution
Step 1: Recall C# variable declaration syntax
In C#, access modifier comes first, then type, then variable name.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.Final Answer:
public int score; -> Option CQuick Check:
Access modifier + type + name = correct declaration [OK]
- Putting 'public' after variable name
- Using 'integer' instead of 'int'
- Incorrect order of keywords
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);
}
}Solution
Step 1: Understand JsonUtility.ToJson output format
JsonUtility converts object fields to JSON string with keys and values in quotes where needed.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.Final Answer:
{"playerName":"Alex","level":5} -> Option DQuick Check:
JsonUtility outputs valid JSON string [OK]
- Missing quotes around string values
- Using invalid JSON syntax
- Thinking JsonUtility needs MonoBehaviour object
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);
}
}Solution
Step 1: Check if Player class can be serialized
JsonUtility can serialize plain classes with public fields, no need to inherit MonoBehaviour.Step 2: Check output of JsonUtility.ToJson
Player's score defaults to 0, so JSON string will be {"score":0}.Final Answer:
No error; code will output {"score":0} -> Option AQuick Check:
Plain class with public fields serializes fine [OK]
- Thinking class must inherit MonoBehaviour to serialize
- Assuming private fields serialize by default
- Believing JsonUtility requires static context
Solution
Step 1: Understand JsonUtility serialization rules
JsonUtility serializes public fields or private fields marked with [SerializeField] attribute.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.Step 3: Choose best practice
Using private fields with [SerializeField] is recommended for encapsulation and serialization.Final Answer:
public class Settings { [SerializeField] private float volume; [SerializeField] private string username; [SerializeField] private bool isFullScreen; } -> Option BQuick Check:
Private fields + [SerializeField] serialize correctly [OK]
- Assuming private fields serialize without attribute
- Using properties instead of fields for serialization
- Ignoring encapsulation best practices
Ready to prove it?
Pass the test and this pattern moves unknown
