0

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.

  • 2
    This code doesn't even compile. Please give actual code or we can't help. – DavidG Mar 09 '22 at 15:35
  • OK, now we have some more realistic code, there's no way for the `Awake` method to be called without creating an instance of the class. – DavidG Mar 09 '22 at 15:41
  • 2
    Jon Skeet does a very good job explaining how to implement a Singleton [here](https://csharpindepth.com/articles/singleton). – Icemanind Mar 09 '22 at 15:41

1 Answers1

0

In your class you never create the instance of the class. With singleton pattern you should do it when declaring static isntance object:

public static Stat_player instance = new Stat_player();
  • Thank you for you answer, I thought the method ```Awake()``` from unity has been called, but it was never the case, so I resolved the problem by attaching the script to a gameObject which allows the method to be called, and the instance initiated. –  Mar 09 '22 at 16:14
  • Using `new` on something inheriting from `MonoBehaviour` is "not allowed". It makes no sense since a valid component can only exist attached to an according `GameObject`. – derHugo Mar 10 '22 at 08:01
  • However, @Rimo, does your class even need to be a `MonoBehaviour`? Is it necessary that it is attached to a `GameObject` and do you even use any of the `MonoBehaviour` event methods (`Update`, `OnTriggerEnter`, `OnMouseDown`, `etc ...)? Because if not your `Stat_player` could as well be a `public static class`, only contain `static` members and there would be no need for a singleton pattern whatsoever ... – derHugo Mar 10 '22 at 08:03