How to save a reference to a GameObject?

In the Unity editor, I can save a reference to a GameObject. I just go to the script component in the inspector, and select the GameObject I want for any public variable. I can load and re-load the scene as much as I want and that variable will always point to exactly the GameObject I specified.

I want to do the same thing at runtime. I want to get a GameObject reference and save it to file. I don’t need to save any properties of the GameObject, I just need the reference. It’s possible for Unity to do it, but I’ve searched and searched and can’t figure out how we can do it.

I need something like:

// Remember thatOne
MagicReference rememberThat = GetGameObjectReference(thatOne);
SerializeToFile(rememberThat);
...
MagicReference loadedReference = UnserializeFromFile();
GameObject whichOne = FindGameObjectByReference(loadedReference);
// whichOne = thatOne

Does anyone have any ideas?

Thanks!

The technique described in this article will serve you well:

Seems this is a common problem with no easy answer…