S&box Wiki

Triggers

What is a trigger

When a collider component is marked as a trigger, other physics objects pass right through and can detect when they enter or exit the collider.

Detecting Triggers

To detect when an object enters or exits another collider, both GameObjects must have a collider component attached(box, sphere, etc), with the Is Trigger box checked on one of them.

For a component to detect triggers, it must be on the same GameObject as one of the collider components.

image.png

First inherit from Component, Component.ITriggerListener, then implement public void OnTriggerEnter() or public void OnTriggerExit, public void is necessary. In the parenthesis, add Collider other to get the entered / exited collider component or GameObject other to get the GameObject it is on.

public sealed class TriggerExample : Component, Component.ITriggerListener, Component.ICollisionListener { // Called when we enter a trigger collider, sets "other" variable to the collider component we entered. public void OnTriggerEnter( Collider other ) { Log.Info( $"Entered Trigger{other.GameObject.Name}" ); } // Called when we exit a trigger collider, sets "other" variable to the gameobject we exited. public void OnTriggerExit( GameObject other ) { Log.Info( $"Left trigger {other.Name} " ); } }

Alternatively, with RigidBody.Touching we can get a list of all colliders intersecting us

// Gets or creates a RigidBody component on this GameObject [RequireComponent] private Rigidbody rb { get; set; } protected override void OnFixedUpdate() { // Prints the amount of colliders we are intersecting to the console Log.Info( rb.Touching.Count() ); }