Unity turning on/off collision in C Sharp

Hi Guys,

Trying to do the equivalent of turning on/off collision (Mesh Collider) in script. I’m happy however it works, either removing then re-adding the mesh collider component, or by switching between a trigger and collision in script.

Is there a way to do this in Unity?

Simply set the ‘enabled’ property of the collider to false. This goes for any GameObject component (any class that inherits the Component class).

public Collider myCollider; // set this in the inspector
...
myCollider.enabled = false;

In addition to Brian’s response, you can also do (somewhat easier)

theGameObject.collider.enabled = false;

where theGameObject is any Game Object (if you want to refer to the object that the script is connected to without using a variable, instead you can type in

gameObject

NOT GameObject. gameObject is a premade variable that contains the info the script is attached to. GameObject is the variable TYPE.

IF there is an exception where the object doesn’t have a collider, but the code is being run anyways, you can set an if statement as so:

if (theGameObject.collider != null) {

//then do the stuff you wanna do to make the collider true/false

}

this just checks if the component doesn’t return null (which means that a collider exists)

Very informative guys, thanks :slight_smile: