Can I enable/disable a collider so it will/won't detect mouse clicks?

I have some 'billboard' planes I use as UI objects in my scene. They have mesh colliders on them so I can detect when user mouse-clicks on them. I need to hide/show these things. The problem is, even hidden, the colliders are intercepting mouse-clicks, such that an invisible one in front of a visible one will 'hide' the visible one, so the visible one does not detect mouse clicks (I hope that made sense).

Is there a way to 'disable' a mesh collider such that it won't intercept the click? It has no 'enabled' field. Note that the renderer is disabled, that alone was not enough to disable the collider.

Or is there a better way to do mouse-clicks?

Well, this doesn't solve the actual problem (disabling collider/mouse), but it's actually a cool work-around which works very well for me, so I'll share it: When I need to disable (hide) my collider, I use the Update function to reduce the scale (over time) to zero, and when I show it, return scale to 1. This shrinks the colliders so they are out of the way, and has the added bonus of looking cool while it's doing it.

What you can do is to put the object on another layer by setting its layer property and then excluding that layer when raycasting. You perform the hit test as follows (the excluded objects are on layer 8 in this example):

RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),
    out hit, Mathf.Infinity, ~(1 << 8))) {
    print("It's a hit!");

See also: Layers in Unity documentation

Like Markq mentioned the best way is to use layers. If you just want to enable / disable the OnMouseXXX events of a certain GO use this:


// disable Raycasts
gameObject.layer = 2;

// enable Raycasts (set to default layer)
gameObject.layer = 0;

Layer 2 (start counting by 0) is the IgnoreRaycasts layer if your GO is on that layer it will be ignored by unity.

Yea, I don't think you can enable/disable colliders like some of the game objects other components. I could be wrong...but... you could "destroy" the collider when you don't want it used then "addcomponent" it when you want it...

I'm not sure if this is the best way, I'm still very new to Unity...

Hi, you can do this…

[SerializeField] private LayerMask inputLayerMask;
private void Start()
	Camera.main.eventMask = inputLayerMask;

Then in the game object’s inspector set what layer mask, or masks, you want to receive mouse input.