Sign In Register

How can we help you today?

Start a new topic

GameSparks GameObject Singleton (Unity)

Problem:


The GameSparksUnity.cs script marks the object in which it's attached as DontDestroyOnLoad. Suppose you have a first scene in your game where you create this object (e.g. your main menu). Every other scene will have access to this game object. But, what if you're developing another scene, which you want to test independently while you develop without changing to your initial scene before running the game. You need to add another GameSparksUnity object to your hierarchy... now, what happens when you test your game running from that initial scene, and eventually reach the scene you were developing where you created another GameSparksUnity object? You will now have 2 instances. What if this scene is something that you can access many times? You will have many don't-destroyed-on-load instances of this object.


Solution


Add this code to GameSparksUnity.cs to make it singleton, thus preventing multiple instances:


 

private static GameSparksUnity instance;
public static GameSparksUnity Instance {
    get{ return instance; }
}
 
private static object singletonLock = new object();
 
private void Awake() {
    lock(singletonLock) {
        GameSparksUnity[] instances = GameObject.FindObjectsOfType<GameSparksUnity>();
        if(instances != null && instances.Length > 1 && instance != this) {
            Debug.Log("Destroying duplicate GameSparksUnity game object.");
            Destroy(this);
        } else {
            instance = this;
        }
    }
}

   You're welcome ;)


Thanks again Eduardo!

 

nice

Login to post a comment