Once I seek for “Unity persistent ID”, the primary result’s the documentation for UnityEditor.GlobalObjectId, which appears to do precisely what you need:
Distinctive and steady project-scoped identifier for objects in scenes and in different forms of belongings to be used at authoring time.
Use this struct to acquire distinctive identifiers to things which might be a part of scenes or inside different belongings comparable to prefabs and ScriptableObjects. The identifiers are steady and chronic throughout enhancing periods and knowledge serialization operations, comparable to altering the energetic scene and saving and reloading.
We will get a serializable model of this ID for a scene object, prefab, or youngster of a prefab with:
string id = UnityEditor.GlobalObjectId.GetGlobalObjectIdSlow(gameObject).ToString();
This string is exclusive and steady throughout getting into/exiting play mode and shutting/re-opening the editor. This additionally works for different forms of belongings, or to reference particular person elements on on object – simply commerce gameObject
for the suitable reference.
For objects in an open scene, the one caveat is that you might want to save the scene no less than as soon as after the article is created, earlier than it will get assigned a world ID.
To parse such a serialized string again into an ID, you need to use:
UnityEditor.GlobalObjectId.TryParse(stringId, out var idStruct);
Then yow will discover the article with this ID with:
var object = UnityEditor.GlobalObjectID.GlobalObjectIdentifierToObjectSlow(idStruct);
or if you happen to simply want its occasion ID:
int instanceID = UnityEditor.GlobalObjectID.GlobalObjectIdentifierToInstanceIDSlow(idStruct);
These will fail (returning null
or zero, respectively) if the article you are wanting up is in a scene that’s not at the moment loaded, or if it could actually’t be discovered (e.g. asset was deleted, or the enter was malformed).
There are additionally array variations of every of those that may work on a batch of IDs at a time. This helps amortize the efficiency value throughout a number of operations, since as the strategy names point out, they’re “gradual” — the value we pay for assured international uniqueness and stability.