keep static/global object through scenes

Hello,

Is there a good way to keep an object available while changing scenes?
I read about the ‘DontDestroyOnLoad’ method, but I don’t understand how I can get a reference to that object so I can access it in the scripts that are loaded in the new scene.

Something like a global object would do the job.

An example would be nice, I’m currently struggling with going from my ‘lobby’ scene to the ‘in-game’ scene without losing the connection I just setup (I use my own Networking implementation and need to keep the ‘Client’ & ‘Server’ objects to send messages while in-game)

So either

  1. Find it in each scene you need it using GameObject.Find or something similar.

  2. Create a static variable and reference it.

    public class PermanentObject {
         public static Dictionary<string, GameObject> lookup = new Dictionary<string, GameObject>();
         void Awake() {
             if(lookup.ContainsKey(name)) Destroy(lookup[name]);
             lookup[name] = gameObject;
             DontDestroyOnLoad(gameObject);
         }
         void OnDestroy() {
             if(lookup.ContainsKey(name) && lookup[name] == gameObject) lookup.Remove(name);
         }
    }
    

Then you can find them using

    var obj = PermanentObject.lookup["SomeName"];