10.8 C
New York
Friday, March 14, 2025

unity – Can’t discover a persistent ID between editor classes for an object


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 are a part of scenes or inside different belongings comparable to prefabs and ScriptableObjects. The identifiers are steady and chronic throughout enhancing classes and information serialization operations, comparable to altering the lively scene and saving and reloading.

We are able to 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 coming into/exiting play mode and shutting/re-opening the editor. This additionally works for different forms of belongings, or to reference particular person parts on on object – simply commerce gameObject for the suitable reference.

For objects in an open scene, the one caveat is that it is advisable save the scene not less than as soon as after the item is created, earlier than it will get assigned a worldwide ID.

To parse such a serialized string again into an ID, you need to use:

UnityEditor.GlobalObjectId.TryParse(stringId, out var idStruct);

Then you’ll find the item 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 item you are wanting up is in a scene that isn’t at the moment loaded, or if it could’t be discovered (e.g. asset was deleted, or the enter was malformed).

There are additionally array variations of every of those that can work on a batch of IDs at a time. This helps amortize the efficiency value throughout a number of operations, since as the tactic names point out, they’re “sluggish” — the value we pay for assured international uniqueness and stability.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles