1
\$\begingroup\$

I'm trying to serialize the state of play of my Unity game (Unity 2021.3.7f1) to JSON using UnityEngine.JsonUtility.ToJson, so that I can persist this state to disk and load it on demand.

However, for some reason I don't know of, JsonUtility.ToJson is not serializing every field in the class (or rather, fields of the instances held in some of the fields of this class) that represents the game state.

Here's this class (GameState):


[System.Serializable]
public class GameState
{
    public List<Ball> balls;
    public List<HitBlock> boxes;
    public List<ExtraBallPowerup> extraBallPowerups;
    public List<Bomb> bombs;
    public bool bStartNewGame;
    public uint iNumBalls;
    public uint iNewNumBalls;
    public float ballStartPositionX;
    public uint timesEscapedDeath;
    public uint iTurnCounter;
    public DifficultySetting difficultySetting;
}

The classes (HitBlock, ExtraBallPowerup, and Bomb) of the objects held in the Lists boxes, extraBallPowerups, and bombs all also have the [System.Serializable] attribute set, and they all derive from a common base class called GridObject.

Here is this class GridObject:


[System.Serializable]
public class GridObject : MonoBehaviourExtension
{
    public GridPosition gridPosition;

    protected Vector2 movementTarget;
}

Here is the Struct GridPosition:


[System.Serializable]
public struct GridPosition : IFormattable
{

    public int x;
    public int y;

    public GridPosition(int _x, int _y)
    {
        x = _x;
        y = _y;
    }
    public static implicit operator Vector2(GridPosition gp) => new Vector2(gp.x, gp.y);

    public string ToString(string format, IFormatProvider formatProvider)
    {
        return string.Format("({0}, {1}", x, y);
    }
}

Now, in the main game loop, I create and fill the gameState object, then try to serialize it to JSON.


GameState gameState = new GameState();
//...
//... Run game loop and populate gameState field
//...
var jsonObject = JsonUtility.ToJson(gameState);

Inspecting gameState at this point gives something like this:

enter image description here

However, looking at the jsonObject gives me this:


{
    "balls": [
        {
            "instanceID": -57492
        }
    ],
    "boxes": [
        {
            "instanceID": -57278
        },
        {
            "instanceID": -57326
        },
        {
            "instanceID": -57384
        },
        {
            "instanceID": -57434
        }
    ],
    "extraBallPowerups": [
        {
            "instanceID": -57480
        }
    ],
    "bombs": [
        {
            "instanceID": -57370
        }
    ],
    "bStartNewGame": false,
    "iNumBalls": 1,
    "iNewNumBalls": 1,
    "ballStartPositionX": 0.0,
    "timesEscapedDeath": 0,
    "iTurnCounter": 3,
    "difficultySetting": 2
}

So, apart form the instanceID, none of the fields of the objects held in bombs, hitBlocks, and extraBallPowerups are serialized.

However, I would expect/hope/want for the fields of the object instances held in balls, extraBallPowerups, and bombs to also be serialized in this JSON. Among others, I need the gridPosition field defined in parent class GridObject (highlighted in yellow in the screenshot) as well as some other fields which are defined in these 3 subclasses (e.g. bIsMovingBox, also highlighted in yellow in screenshot), to be serialized into this JSON.

Obviously, when I try to deserialize the JSON as it currently is, I am not able to restore the game state, since said JSON does not include the necessary fields, as just explained.

Why does JsonUtility.ToJson() not serialize all the fields of the stated objects, and what can I do to ensure these fields do get serialized as well?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ What you are storing in those lists is NOT the data of the HitBlock etc objects. It is a reference to an instance that contains that data. If you want to serialize that instance, you must also follow that reference to the instance it refers to in your own code, and serialize that separately. The serializer cannot eagerly follow references, since that could lead to exponential blow-up or an infinite loop in the case where there's a cycle in the reference graph. \$\endgroup\$
    – DMGregory
    Aug 13, 2022 at 19:32

0

You must log in to answer this question.

Browse other questions tagged .