📖 Scenario: You are creating a simple Unity game where you want to save the player's name and score so you can load it later.
🎯 Goal: Learn how to create variables and use serialization to save and load player data in Unity.
📋 What You'll Learn
Create variables to store player name and score
Use Unity's serialization to save player data
Load and display saved player data
💡 Why This Matters
🌍 Real World
Saving player data is essential in games to keep progress between sessions.
💼 Career
Understanding variables and serialization is key for game developers working with Unity to manage game state and data persistence.
Progress0 / 4 steps
1
Create player data variables
Create a public class called PlayerData with two public variables: a string called playerName and an int called playerScore.
Unity
Hint
Use public string playerName; and public int playerScore; inside the class.
2
Add serialization attribute
Add the [System.Serializable] attribute above the PlayerData class to enable Unity to serialize it.
Unity
Hint
Place [System.Serializable] right before public class PlayerData.
3
Create and assign player data instance
In a new GameManager class, create a public variable called playerData of type PlayerData. Then, in the Start() method, first instantiate it with playerData = new PlayerData();, then assign playerData.playerName to "Alex" and playerData.playerScore to 100.
Unity
Hint
Declare public PlayerData playerData;, instantiate with playerData = new PlayerData(); and assign values inside Start().
4
Print player data to console
In the Start() method of GameManager, add a Debug.Log statement to print the player's name and score in the format: "Player: Alex, Score: 100".
Unity
Hint
Use Debug.Log($"Player: {playerData.playerName}, Score: {playerData.playerScore}"); inside Start().
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
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 A
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
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 C
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
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 D
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
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 A
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; } }
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 B