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?`

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.

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.