I think you have this backwards. Rather than have a Score
object that knows about everything that can change the score, you should have all of your objects that might update the Score
know about a single instance (a singleton) Score
object.
Really simple case might be something like:
public class Score
{
public int TheScore { get; private set; }
public static _instance;
public static Instance // I'm using a static property, but you could also create a static "getInstance" method if you prefer
{
get
{
if (_instance == null)
{
// Note: if you are multithreading, you might need some locking here to avoid ending up with more than one instance
_instance = new Score();
}
return _instance;
}
}
private Score()
{
// Note: it's important to have a private constructor so there is no way to make another instance of this object
}
public int AddToScore(int score)
{
// again - if you have multiple threads here you might need to be careful
TheScore += score;
}
}
Now in your object that might update the score, you just:
Score.Instance.AddToScore(100); // adds 100 to the score
Now if you want to get really fancy here, you could abstract the Score
class into an interface IScore
and then use an inversion of control (IoC) container to manage it for you. That way you can decouple the implementation of the class that holds the score from the classes that will consume it.
And of course to get the current score:
int currentScore = Score.Instance.TheScore;
If you want to use events, then you could look at the publisher/subscriber pattern where you'd basically have a singleton that acts as the manager for your events and everybody that need to publish an event (i.e. your Player
class) will publish to it and your Score
class will subscribe to it.