Search Unity

Event Handling

Discussion in 'Entity Component System' started by EvansT, Aug 22, 2018.

  1. EvansT

    EvansT

    Joined:
    Jan 22, 2015
    Posts:
    22
    I'm trying to convert my game to use Hybrid ECS and I was wondering how to handle events and move code from my components into systems. In my current codebase there is an EventManager which is used extensively to pass messages around.

    There are 2 monobehaviours
    Ownership - This component is used to indicate the player which owns this entity
    Visual - Handles everything visual related to the entity such as changing colours, animation.

    There is a method
    Ownership.SetOwner(int playerIndex)
    which currently sets the OwnerIndex, executes some code and then finally triggers an event through EventManager. This event is handled by Visual component to change the color based on the owner. This event is also handles by various other components to execute other game logic. I'd like to know how to refactor this to the 'ECS way'. From other similar threads the common suggestion seems to be to create a new component to represent the event.

    - Right now the SetOwner() method is inside the Ownership component. This method not only sets OwnerIndex, but also executes other code and triggers the OWNERSHIP_CHANGE event. If I expose OwnerIndex directly on the component, any system can directly set the value, and then the required code would not execute, and the OWNERSHIP_CHANGE event would not trigger. I was thinking of moving the SetOwner() method inside a CharacterSystem which would accept an entity ID and take care of doing all that. Is this correct?

    - How should the event be handled? Say I create a component called OwnershipChanged on the entity to represent the event and every othe system interested in that would use it. Who will be responsible for destroying the component? If the component is not destroyed, then the systems would keep on processing the event. For every event, should I have a corresponding system that executes at the end and removes the event components? Or should the system that created the component be responsible for destroying it?

    I'm a little fuzzy on how to handle this scenario. Any pointers in the right direction would be much appreciated.
     
  2. M_R

    M_R

    Joined:
    Apr 15, 2015
    Posts:
    559
    i'd say systems that care about the ownership change should track it with an
    ISystemStateComponentData
    .
    or you have a single system that does that and manages all the OwnershipChanged components (i.e. creating them, then destroying them on the next update)