NullReferenceException: Object reference not set to an instance of an object in Singleton class.
Hello , when I call printCubePotision from other Script. It shows me an error. The Game object cube that is attached to object in hierarchy of scene is not setting to cube variable in SingletonTest script. How to resolve this? Are there any others ways to implement it for singleton classes.
NullReferenceException: Object reference not set to an instance of an object SingletonTest.printCubePotision () (at Assets/SingletonTest.cs:23)
Singleton class:
using UnityEngine;
public class SingletonTest : MonoBehaviour {
private static SingletonTest _singletonTest = null;
public GameObject cube;
public static SingletonTest Instance
{
get
{
if (_singletonTest == null)
{
_singletonTest = new SingletonTest();
}
return _singletonTest;
}
}
public void printCubePotision()
{
Debug.Log("Test: " + cube.transform.position);
}
}
This how I called form other script.
public void OnButtonClick()
{
SingletonTest.Instance.printCubePotision();
}
Please help me is resolving this.
Answer by UnityCoach · Dec 18, 2016 at 02:23 PM
You have to create a game object and add the component to it, you can't have a component lying in memory only. This is how I do it:
public class SingletonTest : MonoBehaviour
{
private static SingletonTest _instance;
public static SingletonTest Instance
{
get
{
if (_instance == null)
{
_instance = (SingletonTest) GameObject.FindObjectOfType(typeof(SingletonTest));
if (_instance == null)
{
GameObject go = new GameObject("SingletonTest:Singleton");
_instance = go.AddComponent<SingletonTest>();
}
}
return _instance;
}
set
{
_instance = value;
}
}
void Awake ()
{
Instance = this;
}
void OnDisable ()
{
Instance = null;
}
}
Your answer
Follow this Question
Related Questions
What does 'new' do in terms of constructors 1 Answer
Referencing monobehaviour singleton from a non-monobehaviour class? 1 Answer
Singleton ScriptableObject unable to Find itself, returns null 2 Answers
Is Something Wrong With My Singleton Pattern? 1 Answer
Editor nullreference error when playing second time 0 Answers