Triggers

BeginnerDesigner

If you set a collider to be a trigger, other colliders no longer bump into it. Instead, they pass through.

The trigger detects when colliders enter it, which you can use to script events. For example, you can detect when a player character enters a room, and use this in your script to trigger an event. For more information, see Events.

Note

Character colliders can't be used as triggers.

Create a trigger

  • Create a collider.

  • In the Property Grid, under the collider component properties, select Is Trigger.

Select 'Is trigger'

Detect trigger collisions

You can see when something enters the trigger using the following code:

  1. // Wait for an entity to collide with the trigger
  2. var firstCollision = await trigger.NewCollision();
  3. var otherCollider = trigger == firstCollision.ColliderA
  4. ? firstCollision.ColliderB
  5. : firstCollision.ColliderA;

Alternatively, directly access the TrackingHashSet:

  1. var trigger = Entity.Get<PhysicsComponent>();
  2. foreach (var collision in trigger.Collisions)
  3. {
  4. //do something with the collision
  5. }

Or use the TrackingHashSet events:

  1. var trigger = Entity.Get<PhysicsComponent>();
  2. trigger.Collisions.CollectionChanged += (sender, args) =>
  3. {
  4. if (args.Action == NotifyCollectionChangedAction.Add)
  5. {
  6. //new collision
  7. var collision = (Collision) args.Item;
  8. //do something
  9. }
  10. else if (args.Action == NotifyCollectionChangedAction.Remove)
  11. {
  12. //old collision
  13. var collision = (Collision)args.Item;
  14. //do something
  15. }
  16. };

For an example of how to use triggers, see the Script a trigger tutorial.

See also