- Home /
Singleton good in one project but null references in other
Hey guys! I've been using this singleton code for my main project and it works well for my needs. However, yesterday I started a new project using the same code pretty much and I get null ref exception on the line:return instance.gamefinished;
using UnityEngine;
using System.Collections;
public class bSingleton
{
private static bSingleton instance;
public bSingleton()
{
if (instance != null)
{
Debug.LogError ("Cannot have two instances of singleton. Self destruction in 3...");
return;
}
instance = this;
}
public static bSingleton Instance
{
get
{
if (instance == null)
{
new bSingleton ();
}
return instance;
}
}
private bool gamefinished;
public static bool GameFinished
{
get
{
return instance.gamefinished;
}
set
{
instance.gamefinished = value;
}
}
}
This is what I am using to get the variable:
if (bSingleton.GameFinished)
{
return;
}
There's no other errors or anything indicating what's wrong.
Any help would be greatly appreciated, thanks!
Answer by ThomasVandenberghe · Dec 06, 2017 at 01:45 PM
Try to do this
public static bool GameFinished
{
get { return Instance.gamefinished; }
set { Instance.gamefinished = value; }
}
Holy $$anonymous$$oly, it works! Now I am puzzled, how did it even work before? It it now just giving the instance ins$$anonymous$$d of the variable that refers to the instance?
Thanks man!
Seems like in the project that it did work, the variable must have somehow been assigned, maybe by calling new bSingleton somewhere. That's why I usually leave the constructor empty, and assign it in the null check where I create the object.
$$anonymous$$akes sense. Thanks again, man.
Just confirmed it, in my previous search I missed it but now found this in a different script's start(): if (ScoreSingleton.Instance == null) { new ScoreSingleton(); }