Loading lessons...
Script Serialization and JSON
Script Serialization and JSON
Serialization is the process of converting data to a format that can be stored or transmitted. Unity uses serialization for the Inspector, saving scenes, and Prefab data.
Serialization Rules
Unity serializes a field if it meets ALL of these conditions:
- It is
public, OR it has the[SerializeField]attribute. - It is NOT
static, NOTconst, NOTreadonly. - Its type is a serializable type (primitives, strings, enums, arrays, List<T>, classes with
[System.Serializable]).
using UnityEngine;
using System.Collections.Generic;
public class PlayerData : MonoBehaviour
{
// Serialized: public field
public int health = 100;
// Serialized: private + [SerializeField]
[SerializeField] private float speed = 5f;
// NOT serialized: private without attribute
private int _internalCounter;
// NOT serialized: properties are never serialized
public string DisplayName { get; set; }
}
Custom Serializable Classes
To serialize a custom class as a single nested field, mark it with [System.Serializable]:
[System.Serializable]
public class WeaponStats
{
public float damage = 25f;
public float fireRate = 0.5f;
public int magazineSize = 30;
}
public class Weapon : MonoBehaviour
{
[SerializeField] private WeaponStats _stats;
}
JSON Serialization with JsonUtility
Unity's built-in JsonUtility class serializes and deserializes objects to/from JSON strings. It only works with classes that follow Unity's serialization rules.
[System.Serializable]
public class SaveData
{
public string playerName;
public int level;
public float[] scores;
}
// Serialize to JSON
SaveData data = new SaveData { playerName = "Hero", level = 5, scores = new[] { 100f, 200f } };
string json = JsonUtility.ToJson(data, prettyPrint: true);
Debug.Log(json);
// Deserialize from JSON
SaveData loaded = JsonUtility.FromJson<SaveData>(json);
Debug.Log(loaded.playerName); // "Hero"
Saving and Loading Files
using System.IO;
string path = Path.Combine(Application.persistentDataPath, "save.json");
// Write
File.WriteAllText(path, json);
// Read
string loadedJson = File.ReadAllText(path);
SaveData save = JsonUtility.FromJson<SaveData>(loadedJson);
TL;DR
- Unity serializes
publicfields and[SerializeField]private fields of supported types. - Properties and static/const/readonly fields are never serialized.
- Mark custom data classes with
[System.Serializable]to nest them in the Inspector. JsonUtility.ToJson()andFromJson<T>()handle JSON conversion of serializable types.- Use
Application.persistentDataPathfor a cross-platform safe file save location.