Unity Physics — Triggers

Gerald Clark
2 min readJul 5, 2024

--

I’ve covered triggers in my past articles but this is a little deeper dive. Just for clarity< I have a trigger collider set up with a Trigger.cs script attached to it.

So OnTriggerEnter fires when a collider with a rigidbody comes into contact with a tigger collider. We’ve all seen this before:

Here I’m getting the Renderer of whatever object passes through the trigger collider and then changing the color of the material to blue.

This scenario shows a red barrel turn blue when it collides with the trigger object.

Now I’m going to get a little deeper into some of the Material class properties. Instead of accessing the material.color, I’m actually using the SetColor method of the Material class to access the “_EmissionColor” and then set it to green and then I’m multiplying that value by 10 to exaggerate the result.

So you can do a lot of stuff with trigger collision in Unity.

The OnTriggerExit method does the exact opposite thing the OnTriggerEnter method does. When something leaves thee trigger collider, the OnExit method is called.

The On TriggerStay method is something that is used generally when an object has entered and hasnt left yet. This is called once every physics update. (FixedUpdate).

So it isnt the most reliable thing to use if you need something to be checked every frame. For things that need to be a little more accurate, I like to use a bool and set it when you enter and then set it to the other value when you leave. For example:

Now whatever the hasABarrelInIt variable drives can be a little more precise with WHEN things enter and exit the collider.

--

--

Gerald Clark
Gerald Clark

Written by Gerald Clark

Father Game Developer Music Composer Sound Designer

No responses yet