How do I get a reference to a gameobject from its GUID?

I’m looking for a way to assign each NPC a globally unique identifier that will persist from scene-scene and from session to session. GUID seems to be the way to go, and I get that I can create and assign a GUID via:

public System.Guid uniqueCharacterIdentifier;
uniqueCharacterIdentifier = System.Guid.NewGuid ();

I also gather that the simplest way to serialize my IDs would be to write it with .ToString(), and convert it back via uniqueCharacterIdentifier = new Guid(guidAsString);

Where I’m stuck is this: given the GUID for an NPC I want to retain a reference to, how do I actually get that reference? Is there something in the API that converts a guid to the object it’s assigned to?

Get the path from the guid by using: AssetDatabase.GUIDToAssetPath()

Then load asset by using AssetDatabase.LoadAssetAtPath()

Hey,

If you are looking to use the guid at runtime you are out of luck with Assetdatabase, as it’s Editor only.

What you need to do is create a manager; staic or not. Your NPCs would add themselves On Enable. Then when you want one by ID you just ask your manager to look over all NPCs and return the one with the correct ID.

When you say you are using GUID from system that is a bit overkill. Your prefab will not be unique since you said one might be in each scene. In your case you should use the type of class; if all inherit from a base class or an enum. An enum that would be much easier to work with. A guid is not easy to follow.

Cheers,

Side note I will add a code example later but it’s a nightmare to type with auto correct on a phone

Why use an enumeration? You can consider your index into your guid collection as an enumeration.