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
}
}
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:
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)
{
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.