0
0
Unityframework~5 mins

Variables and serialization in Unity

Choose your learning style9 modes available
Introduction

Variables store information your game needs. Serialization saves this information so it can be used later or shared.

You want to remember a player's score between game sessions.
You need to save the position of objects in your game world.
You want to send game data over the internet to another player.
You want to load settings or preferences when the game starts.
Syntax
Unity
public class PlayerData {
    public int score;
    public string playerName;
}

// To save data
PlayerData data = new PlayerData();
data.score = 100;
data.playerName = "Alex";

// To serialize (convert to JSON string)
string json = JsonUtility.ToJson(data);

// To deserialize (convert back to object)
PlayerData loadedData = JsonUtility.FromJson<PlayerData>(json);

Use public variables or [SerializeField] to make variables visible to Unity's serialization.

Unity's JsonUtility helps convert objects to and from JSON format easily.

Examples
This class holds game settings that can be saved and loaded.
Unity
public class GameSettings {
    public float volume = 0.5f;
    public bool isFullScreen = true;
}
This converts the settings object into a JSON string and prints it.
Unity
GameSettings settings = new GameSettings();
string json = JsonUtility.ToJson(settings);
Debug.Log(json);
This loads settings from a JSON string and prints the volume value.
Unity
string json = "{\"volume\":0.8,\"isFullScreen\":false}";
GameSettings loadedSettings = JsonUtility.FromJson<GameSettings>(json);
Debug.Log(loadedSettings.volume);
Sample Program

This Unity script creates a player data object, saves it as JSON, then loads it back and prints both steps.

Unity
using UnityEngine;

public class SerializationExample : MonoBehaviour {
    [System.Serializable]
    public class PlayerData {
        public int score;
        public string playerName;
    }

    void Start() {
        PlayerData player = new PlayerData();
        player.score = 250;
        player.playerName = "Sam";

        // Serialize to JSON
        string json = JsonUtility.ToJson(player);
        Debug.Log("Serialized JSON: " + json);

        // Deserialize back to object
        PlayerData loadedPlayer = JsonUtility.FromJson<PlayerData>(json);
        Debug.Log($"Loaded Player Name: {loadedPlayer.playerName}, Score: {loadedPlayer.score}");
    }
}
OutputSuccess
Important Notes

Mark classes with [System.Serializable] so Unity knows to serialize them.

Only public fields or fields marked with [SerializeField] are saved by Unity.

Serialization helps keep your game data safe between sessions or share it easily.

Summary

Variables hold data your game uses.

Serialization turns data into a format that can be saved or sent.

Unity's JsonUtility makes serialization simple and fast.