How to keep an instance through scenes

Hello everyone, we’re working on our first Multiplayer Application using our Server Backend which is Planned for Open-Source release at a later date, however with using Unity3D we are having an issue with understanding how to keep the instance of the TcpClient connection alive through scenes in the Client. After some research we’ve discovered the method using (DontDestroyOnLoad) however this seems to not work how we want it to, as the Script starts becoming duplicated after loading the same scene multiple times. Basically, what we need to do is have a script that is running throughout the entire lifespan of the application which can be referenced from scripts at any moment. Writing the test-client for this was easy using C#~ However, now that we’re working with Unity and it’s transition of Scenes, how to go about properly doing this is completely boggling our developers minds. I guess that’s one of the things you’ll run into when the team isn’t familiar with the tools provided.

2 Answers

2

The way I plan to do this is by creating all of my persistent scripts in an “Entry” scene - that is never revisited after the game starts. This way I don’t have to worry about duplicates being instantiated and I know all of my objects will follow the player from scene to scene.

This is something we decided on doing, but how would you reference the scripts after you leave said scene. In order to do this would you have to make the Script not directly reference MonoBehaviour?

–

In my situation I have an object called "GameManager" that doesn't get destroyed and is created only once. Any scripts that I want to keep around are kept on this GameManager object. Through this method I know I can always reference the object GameManager to find the scripts I'm looking for - or if I want, I can use a "GameManager" script to act as a script manager. In your case, something like TcpClient tcpClient = GameObject.Find("GameManager").gameObject.getComponent<TcpClient>();

–

Do what @TrevorP suggests or add an “ThereCanBeOnlyOne” script

#ThereCanBeOnlyOne.cs

  using System.Collections;
  using UnityEngine;

   public class ThereCanBeOnlyOne : MonoBehaviour {
            public static ThereCanBeOnlyOne instance;

            void Awake() {
                if(instance != null && instance != this) {
                    DestroyImmediate(gameObject);
                    return;
                }
                instance = this;
                DontDestroyOnLoad(gameObject);
            }
   }

The problem with this script is that's it's usable only once in the project, if you added it to different objects, only one of them would be preserved

–

I think adding Object.GetInstanceID() to the instance ID might work?

–