Hello, I’ve been trying to implement a singleton that is used for managing a grid for a game world, all in c#. The singleton is instantiated in one class attached to a gameobject, and I plan to have the singleton accessible to other classes/scripts. I have the following implementation set up, but I run into problems during run-time with null exception being thrown, the location of the error is pointed at bellow in one of the comments. Here’s the implementation:
public class WorldGrid {
private static WorldGrid _instance = null;
private int[,] grid;
private GridCoord[] dir;
private int sizeX;
private int sizeY;
public WorldGrid Instance {
get {
if(_instance == null){
_instance = new WorldGrid();
}
Debug.Log ("Instance called");
return _instance;
}
}
private WorldGrid(){
}
public BuildGrid(){
//code
}
//Other methods
}
//and when I want to use the singleton in another class..
public class classTest : MonoBehaviour {
private WorldGrid grid;
public Start() {
function();
}
function(){
grid.Instance.BuildGrid(); // Null reference exception at runtime
}
}
Any ideas on why the singleton did not instantiate? Does the singleton have to be a monoBehaviour class? I haven’t seen any resources on this.