Reference problem
Hello, Unity Answers. I have a compiler problem with a reference I made. I know questions like these sound lazy but I've been researching for the past hour and frankly, I'm stumped.
I'm working on a Rogue-like game and the problem occurs in my GameManager script. I need a reference to the spawnRoom object to access it's position, then spawn the player in that room. The spawnRoom object is a public field of the MapGenerator class (inherits from monodevelop). To allow other classes to access the MapGenerator, I created a singleton pattern so I can access fields of MapGenerator like so:
MapGenerator.instance.field;
The compiler error is in the Start method of my class GameManager : monodevelop.
//Runs on start
private void Start()
{
createSingleton();
spawnPlayer(MapGenerator.instance.spawnRoom);
}
Other notes:
I narrowed the problem down to the spawnRoom object. I get an error when I try to access spawnRoom that reads, Object reference not set to instance of an object. I know what this means, I don't know why I'm getting the error.
spawnRoom is defined in MapGenerator properly.
The MapGenerator instance is public & static & defined before GameManager starts.
Any help or resources you can point me to would be greatly appreciated.
Answer by IgorAherne · Feb 24, 2017 at 04:46 PM
null reference means you are trying to do something on an empty "socket", an empty variable which is null.
if MapGenerator.instance.spawnRoom
is returning an error, it's not because spawnRoom is null. Instead, it's because you are trying to get spawn room from a non-existing instance of MapGenerator. In other words, trying to get something from a null-entity.
Your singleton instance is not created correctly, check why .instance
returns null.
class MapGenerator : Monobehavior{
private static MapGenerator _instance;
public static MapGenerator instance{
get{
if(_instance == null){
_instance = Component.FindObjectsOfType(typeof(MapGenerator)) as MapGenerator;
}
if(_instance == null){
_instance = new GameObject("MapGeneratorGO").AddComponent(typeof(MapGenerator)) as MapGenerator;
}
return _instance;
}//end get
}
@IgorAherne your explanation was clear and concise. I think I can fix my problem now, thanks a bunch! (: