I am trying to build a simple system for saving my game state to a JSON file, but I keep getting blank JSON. I have read many posts on this forum and on Stack Overflow from people with similar issues, but in all of the issues I have seen, the issue boiled down to the player trying to serialize a complex type (e.g. a Dictionary) that Unity’s JsonUtility cannot serialize. But I am getting blank JSON even with primitive types, e.g. integers.
Here is a minimal example:
1. Create an empty 3D project and generate two C# scripts as follows:
GameData.cs, a class for holding the data:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class GameData
{
public int score { get; set; }
public int health { get; set; }
public GameData(int score, int health)
{
this.score = score;
this.health = health;
}
}
SaveLoadManager.cs, which will write the JSON to a file (in this case, we just write to the console to keep things simple):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveLoadManager : MonoBehaviour
{
void OnMouseDown()
{
SaveJson();
}
void SaveJson()
{
var data = new GameData(4, 5);
var serializedData = JsonUtility.ToJson(data);
Debug.Log($"Serialized data: {serializedData}");
}
}
2. Create an empty cube and add the SaveLoadManager.cs script to it.
3. Play the game and click on the cube. The following is logged to the console:
(“Serialized data: {}”)
Why is my JSON empty?
(Unity v2021.3.16f1 on Windows 10.)