- Home /
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?
If a script holds a reference to the NPC GameObject, have it also hold a reference to that GameObject's GUID. $$anonymous$$ake sure that this reference gets saved. After loading, cycle through all GameObjects in the scene and access their GUIDs until you get the right one, and re-establish the GameOject variable reference.
Answer by ZenithCode · Sep 07, 2014 at 01:08 PM
Get the path from the guid by using: AssetDatabase.GUIDToAssetPath()
Then load asset by using AssetDatabase.LoadAssetAtPath()
I'm working on implementing this now- based on the unity docs, I'm doing:
string test =AssetDatabase.GUIDToAssetPath (uniqueCharacterIdentifier.ToString());
testCharacter= AssetDatabase.LoadAssetAtPath (test, typeof(GameObject)) as GameObject;
Debug.log statements confirm that unique IDs are being generated, but the second line isn't working- testCharacter remains blank after this runs. Is there an obvious error I'm perpetrating?
Answer by BMayne · Sep 11, 2015 at 12:30 AM
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
Answer by Leith_Ketchell · Oct 13, 2018 at 11:34 AM
Why use an enumeration? You can consider your index into your guid collection as an enumeration.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Big Problem Serializing 0 Answers
Multiple Cars not working 1 Answer
Instantiating Prefabs through Editor Script 1 Answer
How do I keep references to unique NPCs between scenes? 1 Answer