Hello,
I am having weird behaviors using the Component based Singleton example found on the Unify Wiki. I have a feeling that I am not implementing it correctly. So, I was using the following code to "instantiate" a Singleton GameObject, and it was working.
static MySingleton singleton = new MySingleton();
I messed around with other parts of the project and now the Singleton GameObject is not being create, in fact the following section of the MySingleton class is not tracing anything.
if (instance == null)
{
print("Make new Singleton GameObject");
instance = new GameObject ("MySingleton").AddComponent<MySingleton> ();
}
Any help on how to use the Component based MySingleton example would be greatly appreciated. Thanks
You've mixed and matched the component and non-component based singletons. The first code snippet you posted only works for non-component singletons. You need to use the instance declaration from the component example, namely: `private static MySingleton instance;`
The second code snippet you posted only gets executed if there isn't an instance of the component in the scene. Using the component-based singleton, it's possible to add the component to a scene manually (as you would any other Monobehaviour). If you've done so, that print will never occur. It's basically there as a fail-safe in case you haven't manually added your MySingleton object or have destroyed it (by loading a new scene, etc).
To refer to the MySingleton instance, you'd call `MySingleton.Instance` and then treat it as you would any other instance of a MonoBehaviour.
As a tip, if you want your MySingleton to stick around between levels, you'll need to add `DontDestroyOnLoad(gameObject);` in Awake.
You should be getting editor warnings saying you can't create monobehaviours from the New keyword, because you can't. You can however, use Awake, and not the constructor.
The way I prefer to do this for a component is like so:
public class MySingleton : MonoBehaviour {
static MySingleton instance;
void Awake(){
if(instance ==null){
instance = this;
}
else{
Debug.LogWarning("There should only be one of these");
}
}
}
Hey there. I’ve been using a lot of singletons in my project and doing the same code again and again got annoying, and it take quite a lot of lines, which leaves a lot of room for stupid mistakes. So I looked for a way to make this easier. Didn’t found any but I found this thread.
Anyway, I did it myself, if anyone is interested, it’s on the wiki all the way down. To use it, you inherit from MonoSingleton instead of MonoBehaviour, you declare Init() instead of Awake() and you’re good to go. Example :
public class MySingleton: MonoSingleton< MySingleton >
{
public override void Init (){}
public void Whatever(){}
}
// In an other file
public class OtherClass: MonoBehaviour
{
void Start ()
{
MySingleton.instance.Whatever();
}
}