0

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
    }

}
0

2 Answers 2

1

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)
     {
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Oke, but then if I call this function from any class, I want FunctionCalledWhenStateChanges() to be called in all derived classes. How would this be possible?
@JorisKok All those derived classes. Is there a single instance of any derived type, or are there multiple instances. If so; you will need the Observer Pattern (and upvote @MartinMulder).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.