How to uniquely identify a gameobject across multiple playthroughs? GameObject.InstanceID?

I want to save the state of components in my game and for this I need a persistent (across multiple play sessions) and reliable way to identify a gameobject.

Once a gameObject is created in the editor can it ever change its InstanceID?

The way I read it, the ID you receive is only guaranteed to be unique, not to be the same across multiple play-thoughs. That being said, why don’t you use GameObject.Name with your own UID scheme? Since you are using Editor, you might as even create an Editor command for that.

-ch

The problem with using the name of the object is that I must have to have different names for all the objects I save which might hard to guarantee. Is that what you suggest?

Yes. The Name is guaranteed to persist through reruns.

Yes but if I have to save 500 triggers, I must be extremely careful not to name these triggers the same way. I’d rather it be a number that’s unique somehow.

I recommend that you write a small script that you execute from Editor that assigns a unique Name. Every time you assign such a name to a GO, the script saves the new Counter to a text file, and increments. Since you can assign shortcuts to such Editor scripts, assigning a unique Name is only a keypress away. I’m using a similar script to make builds/compile runs unique

For one of my current projects I need to be able to reference things across both play sessions and scenes. For this I made a component called “PersistentObject” which generates a GUID when instantiated, and adds itself to a static collection. When destroyed it removes itself from that collection. I also have a bunch of utility methods to look objects up via the GUID of their PersistentObject component, and a bit of custom Editor code for hooking them up.

Unity have a blog post (Spotlight Team Best Practices: GUID based references) on a very similar system of their own. If I hadn’t already made my own I’d probably have used theirs. I think the underlying principles are the same, but their Editor integration is nicer than mine. :slight_smile:

1 Like

Thank you :slight_smile:

1 Like