Accessing managers from game entities/components

Posted by Boreal on Game Development See other posts from Game Development or by Boreal
Published on 2012-03-19T16:20:02Z Indexed on 2012/03/19 18:15 UTC
Read the original article Hit count: 256

Filed under:

I'm designing an entity-component engine in C# right now, and all components need to have access to the global event manager, which sends off inter-entity events (every entity also has a local event manager).

I'd like to be able to simply call functions like this:

GlobalEventManager.Publish("Foo", new EventData());
GlobalEventManager.Subscribe("Bar", OnBarEvent);

without having to do this:

class HealthComponent
{
    private EventManager globalEventManager;

    public HealthComponent(EventManager gEM)
    {
        globalEventManager = gEM;
    }
}

// later on...
EventManager globalEventManager = new EventManager();
Entity playerEntity = new Entity();
playerEntity.AddComponent(new HealthComponent(globalEventManager));

How can I accomplish this?

EDIT: I solved it by creating a singleton called GlobalEventManager. It derives from the local EventManager class and I use it like this:

GlobalEventManager.Instance.Publish("Foo", new EventData());

© Game Development or respective owner

Related posts about c#