Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

ECS tracking global state, eg. current mouseover entity

Discussion in 'Entity Component System' started by hellholegames, Feb 5, 2020.

  1. hellholegames

    hellholegames

    Joined:
    Dec 19, 2019
    Posts:
    3
    Please follow this train of thought:

    I want a door entity to open/close upon mouseclick.

    You could have a MouseInteractionComponent with IsClickedInThisFrame and a matching MouseInteractionSystem that sets that flag. Another System, eg. DoorCommandSystem could query for (DoorComponent+MouseInteractionComponent) and open the door when IsClickedThisFrame == true...

    But, you KNOW by design that only one entity can be clicked at a time, so why do the heavy querying over all the Falses to find the single True?

    So: is there an elegant way to store global state in general, where the MouseInteractionSystem can just store a reference/id to the currently clicked Entity so all specific systems who are interested can just go get that one Entity there?

    (actually I have this question in classic Unity too... I miss Scene-state? Not Singletons because they are poor design: they are scoped to the entire program, while they should be scopable to where they make sense (a global list of bullets should be gone when exiting to the menu etc)
     
    Last edited: Feb 5, 2020
  2. swejk

    swejk

    Joined:
    Dec 22, 2013
    Posts:
    20
    In such cases, I usually have singleton component such as:
    Code (CSharp):
    1. struct SelectedEntity : IComponentData
    2. {
    3.     Entity Value;
    4.     bool IsSelectedThisFrame;
    5. }
    Then In a DoorCommandSystem I would get that singleton component, check if SelectedEntity.Value has door component and run any logic I want on that.

    Alternatively, you can add this component directly on the entity with Door Component when it is selected. (in such case you dont need "Value" field in SelectedEntity component).