- Home /
ToolBox singleton nullreferenceexception on reloading scene
Hi , i m trying singleton for the first time and i cant get rid of the null ref exception on reloading of the scene , i saw post where people get already destroyed problem with application quit , but it s not the same i get
so i have the toolbox setup
using UnityEngine;
using System.Collections;
public class Toolbox : Singleton<Toolbox> {
protected Toolbox () {} // guarantee this will be always a singleton only - can't use the constructor!
//public string myGlobalVar = "whatever";
public bool allRaycastDebugOn = false;
public bool allRaycastDepth = false;
public bool RandomSeed = false;
public string seed ;
//public Language language = new Language();
void Awake () {
// Your initialization code here
}
// (optional) allow runtime registration of global objects
static public T RegisterComponent<T> () where T: Component {
return Instance.GetOrAddComponent<T>();
}
}
the singleton
using UnityEngine;
using System.Collections;
/// <summary>
/// Be aware this will not prevent a non singleton constructor
/// such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
///
/// As a note, this is made as MonoBehaviour because we need Coroutines.
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
if (applicationIsQuitting) {
Debug.LogWarning("[Singleton] Instance '"+ typeof(T) +
"' already destroyed on application quit." +
" Won't create again - returning null.");
return null;
}
lock(_lock)
{
if (_instance == null)
{
_instance = (T) FindObjectOfType(typeof(T));
if ( FindObjectsOfType(typeof(T)).Length > 1 )
{
Debug.LogError("[Singleton] Something went really wrong " +
" - there should never be more than 1 singleton!" +
" Reopenning the scene might fix it.");
return _instance;
}
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) "+ typeof(T).ToString();
// DontDestroyOnLoad(singleton);
//
Debug.Log("[Singleton] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created with DontDestroyOnLoad.");
} else {
// DontDestroyOnLoad(_instance.gameObject);
//
Debug.Log("[Singleton] Using instance already created: " +
_instance.gameObject.name);
}
}
return _instance;
}
}
}
private static bool applicationIsQuitting = false;
/// <summary>
/// When Unity quits, it destroys objects in a random order.
/// In principle, a Singleton is only destroyed when application quits.
/// If any script calls Instance after it have been destroyed,
/// it will create a buggy ghost object that will stay on the Editor scene
/// even after stopping playing the Application. Really bad!
/// So, this was made to be sure we're not creating that buggy ghost object.
/// </summary>
public void OnDestroy () {
applicationIsQuitting = true;
}
}
the methodeextention
using UnityEngine;
using System.Collections;
static public class MethodExtensionForMonoBehaviourTransform {
/// <summary>
/// Gets or add a component. Usage example:
/// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
/// </summary>
static public T GetOrAddComponent<T> (this Component child) where T: Component {
T result = child.GetComponent<T>();
if (result == null) {
result = child.gameObject.AddComponent<T>();
}
return result;
}
}
first script to get the seed string from my toolbox
using UnityEngine;
using System.Collections;
public class ToolBoxTester : MonoBehaviour {
// Use this for initialization
void Start () {
//Toolbox toolbox = Toolbox.Instance;
print("seed = " + Toolbox.Instance.seed);
}
// Update is called once per frame
void Update () {
}
}
and a script that restart the scene on keypress
using UnityEngine;
using System.Collections;
public class RestartGame : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.N)){UnityEngine.SceneManagement.SceneManager.LoadScene(PlayerPrefs.GetInt("currentscenesave"));}//Application.LoadLevel(0);}
}
}
at start everything is fine , i get my seed printed out but ; when i press the reloadmyscene button i get the error
NullReferenceException: Object reference not set to an instance of an object
ToolBoxTester.Start () (at Assets/Scripts/ToolBoxTester.cs:9)
my question is , what should i do to not get this error
thanks
[EDIT]
i have the feeling that my problem is related to if (applicationIsQuitting) {return null;}
in the singleton ; i m tempted to cut it out of the code , but then i dont know how i would be able to detect if i have a buggy ghost object in my scene .
[/EDIT]
Answer by LineKernel · Apr 26, 2016 at 01:30 PM
this is a duplicate http://answers.unity3d.com/questions/624427/using-toolbox-singleton-script-and-reloading-scene.html
the last answer by JASlaughter is working
Your answer
![](https://koobas.hobune.stream/wayback/20220612075014im_/https://answers.unity.com/themes/thub/images/avi.jpg)