- Home /
Singleton reproducing every other scene load
I set up a simple test to see how my singleton script was or wasn't working. I have two GameObjects in the scene, one with CallTheMethod on it and one with TheSingleton on it. The scripts are as follows:
using UnityEngine;
using System.Collections;
public class CallTheMethod : MonoBehaviour {
void Update()
{
if(Input.GetMouseButtonDown(0))
CallItAndDie();
}
private void CallItAndDie()
{
if(TheSingleton.Instance != null)
TheSingleton.Instance.Count();
else
print("No instance found.");
Application.LoadLevel(Application.loadedLevel);
}
}
using UnityEngine;
using System.Collections;
public class TheSingleton : MonoBehaviour {
public static TheSingleton Instance;
void Awake()
{
if(Instance != null)
Debug.Log("Instance is not null: " + " Instance is this: " + (Instance == this) + " Instance's gameObject: " + Instance.gameObject.name);
else
Debug.Log("Instance is null");
if(Instance != null && Instance != this)
{
print("I'm destroying: " + gameObject.name);
Destroy(gameObject);
}
Instance = this;
gameObject.name = "SuperSingleton" + Time.time;
DontDestroyOnLoad(gameObject);
}
public void Count()
{
Debug.Log("One, two, three.");
}
}
I got the following debug messages after clicking six times, can anyone explain what is going on? Objects are getting destroyed every other time, Instance is becoming null and then objects are not getting destroyed and Instance is assigned to new objects that survive. Screenshot of Debug messages
Instance is not "this" by the time you check it, thus it gets destroyed every time before it gets to the line where you assign Instance.
It's actually only getting destroyed every other time the level is loaded. And it's getting reassigned to new Singleton objects that survive. I should say that I clicked six times.
if(Instance == null)
{
Instance = this;
gameObject.name = "SuperSingleton" + Time.time;
DontDestroyOnLoad(this);
}
else
{
Debug.Log("Singleton Instance already existed, destroying.");
Destroy(this);
}
Would this approach work better?
Your answer
Follow this Question
Related Questions
DontDestroyOnLoad & Singleton 2 Answers
FindObjectOfType or FindWithTag 1 Answer
singleton, global vars and dontdestroyonload 2 Answers