I need to use a singleton in my game to stock game stat, but it doesn't work as intended.
Here is an example:
public class Stat_player{
public static Stat_player instance;
/*Unity method*/
public void Awake(){
if(instance != null){
Debug.logError("more than one instance is in use!");
return;
}
else{
instance = this;
}
}
private int hp = default;
private int gold = default;
private string name = default;
public void Set_name(string nameP){
name = nameP;
}
}
public class Character{
public string name = "Mark";
public void Build_character(){
Stat_player.instance.Set_name(name);
}
}
So basically, at the line Stat_player.instance.Set_name(name);
, the console throw me a NullReferenceException, I can't find the reason of why this is happening.
Thank you for your interest!
Edit : thank you guys, I don't know who closed my question before someone actually answered it, nevermind...
So I've found out the reason of "NullReferenceException", what was needed is a gameObject to which attach the script, and once that's done the method Awake()
is called (because it has never been called) and the instance of Stat_player is initiated.