Search Unity

Some beginner EntityComponentSystem questions

Discussion in 'Entity Component System' started by dthurn, Mar 21, 2019.

  1. dthurn

    dthurn

    Joined:
    Feb 17, 2015
    Posts:
    77
    Hi folks, just looking at ECS and I have been having trouble figuring out how to structure some really basic patterns in ECS code. Here's an example:

    Suppose my game features a tank which drives around and has a turret which it uses to shoot at enemies, and I want to program the "shoot" animation. That means that I want to rotate the turret to face a specific enemy and then spawn a projectile which travels towards that enemy.

    Question 1: What is the idiomatic way for an entity to find its child entities? In traditional unity, the Tank prefab might use a direct editor reference or something like GetComponentInChildren to find the Turret GameObject. Would the ECS equivalent be to do something like

    Code (CSharp):
    1. struct TankData : IComponentData {
    2.   Entity TurretEntity;
    3. }
    ? How would the tank go about finding the Entity ID for its turret after it's spawned? What if the turret is a few levels of hierarchy down from the tank?

    Question 2: What is the idiomatic way for an entity to query information about other game objects? For example, maybe I have a shoot component that gets added like this:

    Code (CSharp):
    1. struct ShootData : IComponentData {
    2.   Entity Attacker;
    3.   Entity Target;
    4. }
    Given a "Target" entity, how do I determine the current position of that entity so I can send a projectile towards it? What is the equivalent of Target.GetComponent<SomeComponent>() in ECS code? I want to go from the "attacker" entity to "take this tank entity, find its turret child, rotate that to face this position, then shoot a projectile."
     
  2. eizenhorn

    eizenhorn

    Joined:
    Oct 17, 2016
    Posts:
    2,685
  3. dthurn

    dthurn

    Joined:
    Feb 17, 2015
    Posts:
    77
    Are you referring to Unity.Transforms.Parent? So I guess that would be a way to look up a parent entity from a child, but not really the other way around. I guess it might be possible to look up child Entity IDs at create time inside
    IConvertGameObjectToEntity
    , although I'm not sure there's a way to get that information (would the 'turret' child even have an associated entity when the parent's
    Convert
    runs?).

    For question #2, it looks like
    ComponentSystem.GetComponentDataFromEntity
    is the right way to look up stuff like the position of a random entity, although I'm a little worried about the performance of using that over and over.