Accessing Colliders Through Scripts
Last updated
Last updated
Colliders can be accessed like any other component.
Example of storing a Collider component in a variable:
In the Inspector, the object with the script attached will have the component for the script and this property:
You can click and drag an object with a collider into the field or click the circle target icon on the right to select from a list.
If you want to have collider of the object the script is attached to be stored, use this script in the Start() function:
Although the collider components are named "Box Collider" or "Capsule Collider" etc. in the editor, the component can be referenced as "Collider" in the script.
Here is a script that runs code when objects touch or stop touching (put this after the ending bracket of Update() but before the ending bracket of the class):
In this example, the colliding object's tag is checked so the code only runs when that specific object(s) collide with the object this script is attached to. The if statements can be updated to look at the name, layer, etc. This if statement keeps the code from running when other objects collide or are inside the object.
Here is a script that runs code when objects enter, stay, or exit a collider that has the Is Trigger checkbox checked (put this after the ending bracket of Update() but before the ending bracket of the class):
In this example, the entering object's tag is checked so the code only runs when that specific object(s) enter, stay, and exit the collider of the object this script is attached to. The if statements can be updated to look at the name, layer, etc. This if statement keeps the code from running when other objects are inside the object.
You can update whether or not the collider is a trigger with this code: