JsonUtility can handle instanceId of Unity Objects

Hey

When I have a simple serialisable class that holds a reference to a UnityObject, when I use JsonUtility.ToJson on it, I get the reference translated to {"instanceId": 11314}, and when using JsonUtility.FromJson on that json string, I get a new class instance that has a reference pointing to the same instance of the UnityObject,

from what I understand from the documentation about it, it should be returned Null

example:

private void Awake()
{
    var sprite = Sprite.Create(Texture2D.blackTexture, new Rect(0, 0, 2, 2), Vector2.zero);
    var spriteId = sprite.GetInstanceID().ToString();
  
    var data = JsonUtility.FromJson<Save>("{\"sprite\":{\"instanceID\":<id>}}"
            .Replace("<id>",spriteId ));
  
    Debug.Log(data.sprite == sprite); // this logs True
}
//json example - {"sprite":{"instanceID":15602}}
[System.Serializable]
public class Data
{
    public Sprite sprite;
}

Can any one provide explanation for this behaviour?

JsonUtility simply serializes the serializable fields of the object. I guess for Sprite, that’s just the instanceId.

It’s not really going to help you when your game shuts down and restarts, that instanceId will become meaningless.

Yes I am aware that the instance id will change and is not persistent,
but my question is why does it work in the above code case in the first place, is it intended?
or is it just a side effect of JsonUtility riding on the Unity serializer underneath

Yes.

1 Like