- Home /
Using Singleton but getting a null reference
I have tried looking at other similar questions but nothing seems to get rid of the error i get. NullReferenceException: Object reference not set to an instance of an object I dont know if i have missed something obvious this is my first time using singletons thanks for any help.
The singleton Script
public class ManagerScript : MonoBehaviour {
public static ManagerScript Instance { get; private set; }
public int cameraOverview = 0;
private void Awake() {
if (Instance == null) {
Instance = this;
DontDestroyOnLoad(gameObject);
}
else {
Destroy(gameObject);
}
}
}
Using the singleton
void OnMouseDown() {
if (ManagerScript.Instance.cameraOverview == 1) {
Debug.Log("clicked");
}
}
Do you actually have a managerscript in your scene?
Answer by Legend_Bacon · Aug 10, 2018 at 12:35 PM
Hello there,
I use Singletons quite a bit, and this is usually the structure I use:
#region Singleton
public static ManagerScript Instance
{
get
{
if (instance == null)
instance = FindObjectOfType(typeof(ManagerScript)) as ManagerScript;
return instance;
}
set
{
instance = value;
}
}
private static ManagerScript instance;
#endregion
Otherwise, your "using the singleton" code looks good to me.
Note: You have to make sure your Singleton is placed on an object in the scene.
Hope that helps!
Cheers,
~LegendBacon
I don't know why or how but your code just works, been trying to access my manager from other scripts for over 6 hours, compiler showed no errors but unity did, thank you, you saved me!
Answer by _Eyesgood_ · Jun 07, 2020 at 12:18 PM
I use the same code the OP is using, only I place all my Singleton classes on their own root objects, which I believe DontDestroyOnLoad() requires.
Your answer
![](https://koobas.hobune.stream/wayback/20220612172543im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Where would I call the DoDestroyOnLoad function on my Singleton Script 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
The object of type 'Rigidbody' has been destroyed but you are still trying to access it. 2 Answers
How can I make an object invulnerable to collision with a specific object? 1 Answer