Skip to content

EntityLinkManager Listeners

Adrian Papari edited this page Jan 7, 2019 · 14 revisions

Link Listeners

You can react to established and killed links, and changed or dead referenced entities using per-field listeners.

LinkListener callbacks

LinkListener, or for convenience - LinkAdapter, bind to the field of a component type.

public class Child extends Component {
    public Entity parent; // linked field
}
LinkListener<Child> trigger
::onLinkEstablished(owner, target) child.parent updated after being null
::onTargetChanged(owner, newTarget, oldTarget) child.parent points to new entity
::onTargetDead(owner, deadTarget) referenced entity deleted (field auto-reset to null or -1)
::onLinkKilled(owner, target) component removal - possibly due to entity deletion

Example

Consider a component:

/** anchors this entity to {@code target} entity */
public class Anchor extends Component {
    @EntityId int target = -1;
}

If target entity is deleted, we want to remove the Anchor component, as it no longer points to an active entity.

To remove component with dangling reference:

    world.getSystem(EntityLinkManager.class).register(Anchor.class, 
        new LinkAdapter() {

           // relevant fields are injected by default
           private ComponentMapper<Anchor> mAnchor;

           @Override
           public void onTargetDead(int sourceId, int deadTargetId) {
                // deadTargetId is the deleted entity currently referenced
                // by Anchor, owned by entity with sourceId
                mAnchor.remove(sourceId);
           }
        });
world.delete(targetId); 
world.process(); // fires onTargetDead
Clone this wiki locally