Hello!
I have finished the course and in this lecture it is explained how to create singletons in two ways, one is publicly accessible and the other is just a bit more private. I’m trying to make the ScoreKeeper a true global singleton for easier use as stated in the next lecture.
So I copied the Singleton pattern code from AudioPlayer along with the “GetInstance” method but it requires an instance of an object to do so. This will throw the null reference error:
ScoreKeeper scoreKeeper;
void Start()
{
scoreText.text = scoreKeeper.GetInstance().GetScore().ToString();
}
And that happens because the variable scoreKeeper is null because no value has been initialized on that variable. The way I fixed it was by not creating a variable and just using the ScoreKeeper class itself:
void Start()
{
scoreText.text = ScoreKeeper.GetInstance().GetScore().ToString();
}
But that code will also throw an error stating that the method GetInstance needs an instance of an object, so I made the GetInstance method a static method as well:
public static ScoreKeeper GetInstance()
{
return instance;
}
That way you won’t need an instance to access that method.
But my question is, is this how our loved Gary intended it to be? Because that last part is very important part and it is not explained in the lecture, or am I missing something?