- Home /
How are unity references serialized? (instanceID related)
Hi
I'm building some serializing logic, and I'm trying to serialize a reference to a unityObject. What I have come across is AssetDatabase.GetAssetPath --> AssetPathToGUID. Which works quite well, but not for assets which aren't the "main" asset. And object.GetInstanceID --> EditorUtility.InstanceIDToObject which works even better.
But I wonder how references are serialized in the project by Unity, is it using InstanceIDs?
And is there a risk with using instanceIDs? Are they changed by Unity sometimes?
Lastly, is there a better way to serialize references?
Thanks, Aron
Answer by almo · May 12, 2011 at 05:30 PM
This is not a definitive answer since I'm not an expert, but I don't see anything that changes InstanceIDs, and I see some infrastructure that saves them (I think). So it seems like you can use InstanceIDToObject and GetInstanceID.
That appears to be the case. One thing to check would be to make sure that the instance ID of a particular game object or component is the same from one run of Unity to the next. The docs do say that the instance ID is unique. Note that instance ID's are 32-bit, while asset GUIDs are 128-bit, so obviously they aren't equivalent.
I have more info on this now. It seems the InstanceIDs can change from load to load. Though they do not always do so. They do seem to remain static once the objects are loaded, though.
Yes it seems so, I have experimented and found that they (at least some) change when changing scenes, so if you saved IDs in one scene, they only remain the same as long as you don't change to another scene and back again (usually).
Unity seems to use an object called ReferenceData which contains an instanceID and a variable called "cachedPtr" (int) I'm not sure what it is for, perhaps a pointer to the memory address or something.
Added a request on Unity Feedback: http://feedback.unity3d.com/forums/15792-unity/suggestions/1919441-serializable-unity-object-references
Answer by sigs · Feb 03, 2012 at 04:45 AM
This project seems redundant now that UT is using text-based yaml to serialize scenes and prefabs.