I have spent a long time (4-5 hours) digging around as to why my version of the Breakout Unity Tutorial was not working. There where repeated errors of
NullReferenceException: Object reference not set to an instance of an object xxxxxxx
when running the game and calling Game Manager scripts from other scripts in the game.
After much reading up on vaguely useful questions and answers on here I know well enough what the error text means, but the answers on here that describe the error in detail do not reference how to solve this issue on an instance of a singleton.
Elsewhere I found a solution, and want to show this solution as I figure that can help a lot of other people searching for why this issue occurs:
Qualifier:
There is an inconsistency with the Breakout Tutorial
see the instantiation of the Game Manager class:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GM : MonoBehaviour {
public int lives = 3;
public int bricks = 20;
public float resetDelay = 1f;
public Text livesText;
public GameObject gameOver;
public GameObject youWon;
public GameObject bricksPrefab;
public GameObject paddle;
public GameObject deathParticles;
/***
* The below sets the Game Manager Class (GManager) as an instance so is a
* static variable. This means its accessed via the class rather than via
* an instance of the class.
* This means Game Manager can be reached from other scripts with code
* `GManager.instance.xxx = whatever`
* So only one GManager instance will be running. This is a singleton pattern.
***/
public static GM instance = null;
private GameObject clonePaddle;
// Use this for initialization
void Awake ()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
Setup();
}
public void Setup()
{
...
}
Please read my solution below: