- Home /
Can't access a Singletons instant.
A question regarding Singleton, i guess it should be simple and i am doing something wrong.. the code:
GameManager.cs
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public static GameManager Instance { get; private set; }
private void Awake() {
if (Instance != null) {
DestroyImmediate(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
public void DoSomething(string text)
{
print(text);
}
}
test.cs (test the singletone)
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
// Use this for initialization
void Start () {
GameManager.Instance.DoSomething("got it");
}
// Update is called once per frame
void Update () {
}
}
the question is: why do i get an error: NullReferenceException: Object reference not set to an instance of an object test.Start () (at Assets/test.cs:9)
this line: GameManager.Instance.DoSomething("got it"); Why can't i access it?
Answer by supernat · Apr 03, 2015 at 02:34 PM
Start calls are not in a guaranteed order, so you're lucky you caught this bug. If the GameManager::Start() method was called before the test::Start() method, it would go unnoticed and possibly crash on different platforms. Move the GameManager::Start() code to the GameManager::Awake() method instead, because by the time you get to the Start() call, Unity guarantees that all Awake() methods have been executed on every object.
Secondly, just make sure you have actually attached the GameManager script to an object in the scene.
"Secondly, just make sure you have actually attached the Game$$anonymous$$anager script to an object in the scene" SOLVED IT! :) Also changed Start() to Awake() (changed also in original post to Awake)
Answer by _joe_ · Apr 03, 2015 at 02:37 PM
This problem is probably due to the fact that the Start of class test is being executed before your GameManager class.
You can fix it in 2 ways:
Either change your GameManager Start code and place it in Awake()
Or go to Edit -> Project Settings -> Script Execution Order, and add GameManager.cs and test.cs and make sure that GameManager is above (executes before) test.
+ 1 for the Project Settings reference. I didn't know about that! You can possibly also move the Game$$anonymous$$anager object to the top of the hierarchy in the Hierarchy view, not sure if that will change the call order.
Can't i just add Game$$anonymous$$anager.cs with value 100? if i have like 20 more scripts, i need to add them all to the "Script Execution Order"?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Can anyone help with loading issues when button is clicked? 0 Answers
Kongregate API not connecting C# 2 Answers
How to get a dialog box on selecting a 3d object ? 0 Answers