Question

How can I call a function in all derived classes when a global game state changes?

public abstract class GameStateBehaviour {

    public event EventHandler<GameStateEvents> StateChanged;

    protected virtual void OnStateChanged(GameStateEvents e) {
        // Call this function in all derived
    }

}
Was it helpful?

Solution

If you want to inform other classes about a state change, us use the 'observer pattern' (See: http://en.wikipedia.org/wiki/Observer_pattern). There are two parties:

  • One party is "the object", which will change state. He has the duty to inform the others.
  • The other party is "the observer". Multiple observers want to observe the state change of the object. So they want to be informed.

Try this:

class TheObject
{
    public event EventHandler<GameStateEvents> StateChanged;

    // If your object changes state, this function should be called. It informs all observers by invoking the StateChanged delegate.
    protected virtual void OnStateChanged(GameStateEvents e)
    {
        if (StateChanged != null) 
            StateChanged(this, e);
    }
}

class TheObserver
{
     public TheObserver(TheObject o)
     {
         o.StateChanged += Object_StateChanged;
     }

     // This function is called by the object when the object changes state.
     private void Object_StateChanged(object sender, GameStateEvents e)
     {
     }
}

OTHER TIPS

The OnStateChanged method is the method that should trigger the StateChanged event. Not the method that will handle this event. That is why I have added the FunctionCalledWhenStateChanges method.

public abstract class GameStateBehaviour
{
    public event EventHandler<GameStateEvents> StateChanged;

    protected GameStateBehaviour()
    {
        StateChanged += (sender, events) => FunctionCalledWhenStateChanges();
    }

    public virtual void FunctionCalledWhenStateChanges()
    {
        // The called function
    }

    protected void OnStateChanged(GameStateEvents e)
    {
        if (StateChanged != null) StateChanged(this, e);
    }
}

The solution above handles your own event. I think it is even better to implement the Template Method Pattern instead of responding to your own event. However I think you are not sure where to throw the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top