S&box Wiki

Log in to edit

Triggers

<cat>Code.Physics</cat> <title>Triggers</title> # 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. <upload src="b4aa4/8dd1174da934054.mp4" size="102148" name="sbox-dev_zBUmPyOwxC.mp4" /> # 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. <upload src="b4aa4/8dd117562e0073f.png" size="14607" name="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. ```cs 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 ```cs // 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() ); } ``` <upload src="b4aa4/8dd11772985c5f9.mp4" size="1493000" name="sbox-dev_r2t2mK0s6R.mp4" />