Serialized objects have instanceID change on load.

So I’m seeing something happen and I want to know if someone can confirm is this is to be expected or if perhaps I’m screwing something up.

I’ve got an class that is a few strings and a number of Sprite objects. The class is serializable and I save it to a file using the JsonUtility class. Things look fine, though what ends up getting saved for the Sprites are instanceIDs. So one of the serialized objects will look like:

[ { "objectName": "Test1", "spriteTop": { "instanceID": 5094 }, ...

This all works fine when loading the objects back in and everything. However, I’ve noticed that if I close Unity or restart my computer or something, next time I run things, all the sprites are off by one in their sprite sheet. The data in the Json file hasn’t changed, the instanceIDs are still the same, but the actual sprites on the sprite sheets they point to have changed. Meaning if before the instanceID pointed to sprite 74 of a sprite sheet, now that ID will instead reference sprite 73. If that makes sense, not the easiest thing to explain.

So am I doing something wrong when serializing the sprites to a Json file? Or do I just need to create an alternate way of loading and serializing sprites instead of trying to serialize the actual sprite object?

Unity’s instanceIDs are not GUIDs. They are not ensured to be globally unique. So yes, they can change between sessions. Unity uses them internally when serializing a scene for references to other objects within the same scene. Though for referencing assets which are stored seperately Unity uses the asset id which is an actual GUID. Unfortunately those are used internally by the assetdatabase and Unity doesn’t really provide a proper API for accessing assetIDs are runtime.

So yes, you usually need your own way to serialize the information you need.