(Unity 4.x) OnMouseDown not firing?

I have a project with an ortho camera. Added a new cube and attached a script with an OnMouseDown method to it but it doesn’t get called when clicking the mouse on the cube.

The cube has a collider, the scene is empty except for the cube(so no invisible objects grabbing the raycast), and the script is attached to the cube. Also, the cube is on the default layer (not on the ignore raycast layer). What am I missing?

For reference, here is the code, “started” gets logged but not OnMouseDown:

public class NewBehaviourScript : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Debug.LogError("started");	    
	}

    void OnMouseDown() {
        Debug.LogError("down");
    }
}

Using latest Unity 4.x.

Usually when I see this problem it is due to a collider conflict. That is, OnMouseDown() is raycasting under the hood. If the ray from the mouse position strikes another collider (visible or not), you don’t get the OnMouseDown() call. To debug put the following code on an empty game object. Take a look at what is returned when you click on something that should generate an OnMouseDown() but does not:

using UnityEngine;
using System.Collections;
 
public class RaycastExample : MonoBehaviour {

	void Update () {
		if (Input.GetMouseButtonDown (0)) {
		 	Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		    RaycastHit hit;
		 	if (Physics.Raycast(ray, out hit)) {
				Debug.Log ("Name = " + hit.collider.name);
				Debug.Log ("Tag = " + hit.collider.tag);
				Debug.Log ("Hit Point = " + hit.point);
				Debug.Log ("Object position = " + hit.collider.gameObject.transform.position);
				Debug.Log ("--------------");
		 	}
		}
	}
}

This may be caused by many things, but if you’ve checked all the causes and can’t find anything, it’s probably caused by the distance from the camera. The OnMouseDown implementation uses a depth limit for raycasting which may cause the object to not register the clicks.

Hi radlemur,

I had the very same issue with you. I still do not understand the deeper issue.
What I tried at first was create a new object, apply the script (with no changes) and see if it works. It didn’t work.
What I tried next was restarting Unity and it still didn’t work.
Finally, what I did was delete all objects that referenced that script (including prefabs). Then I created the same objects anew, applied the very same script (no changes whatsoever) and it started working. Since in all cases I was basically working with the default Spheres and Cubes, I think this might be a bug.

No need for raycasting for simple behaviour like that in my opinion, these default events should work (and now they do!).

I hope this helps.

Cheers,
Alex

Thank you all for your input.
So many angles on this.
Of course I did mark this answered way back but failed to include what the actual
answer was.
The solution on my part is totally out of left field.
This problem was happening only in the editor when playing my app.
It turns out it was my Wacom Pad Mouse that was not being recognized.
The cursor will move but clicks are not being registered.
When I plugged in a USB wired mouse it works just fine.
I have updated the drivers for the Wacom Tablet but it hasn’t changed the effect.
So I am just keeping an old USB Mouse around for development.

Hi everyone,
I had this very particular issue once, the real issue here is the Z depth of your box collider, for me Z = (0 to 1) will fire the OnMouseDown but higher values will not do,
this is ideal for 2d games requires no depth as in my case but for 3D youll have to figure what is really going on.,

Hello,

Try this :slight_smile:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
void Start () {
    Debug.Log("started");      
}
    void Update() {
        if (Input.GetMouseButton(0))
            Debug.Log("down");
    }
}

0 = LMB

1 = RMB

2 = MMB

I realize this is marked as answered already but in hopes of helping others who run into this same issue check one more thing off the list of possible causes:

  • check if the item you are clicking is inside another object’s collider.

e.g. I had this occur when I used a short-wide cylinder gameobject as a platform that my “clickable” gameobject stood upon. By default the cylinder primitive has a capsule collider that extends out past the end of the cyclinder which can unintentionally envelope a gameobject you arrange on top of it.

To fix do one of the following:

  1. move the clickable object out of the other object’s collider,
  2. remove/deactivate the other object’s collider, or
  3. change the other object’s collider to a type mesh collider and ensure your clickable is no longer inside it

Hello, my solution is to create the observer pattern.

MouseManager will check the objects you want to know about mouse events or states of the mouse.

IMouseObserver is implemented to perform the specific behavior of each mouse event.

http://www.orunz.com/tuto/mouse_manager.unitypackage

The function name is OnMouseDown and not onMouseDown - this was my problem. Thanks to zerokcm in comments above for pointing this out.

Hi,

The same issue with me , even after doing the options given above i didnt get the event fired so changed the code to be something like this

void Update ()
{
  if (Input.GetMouseButtonDown(0) && this.guiTexture.HitTest (Input.mousePosition) == true) 
    mbMouseDown = true;
  if (Input.GetMouseButtonUp (0))
    mbMouseDown = false;
}

My issue was the object with the collider was not in a layer that was being rendered by the camera… I wanted the collider on a mesh that I could ‘turn’ off when not debugging - broke my OnMouse stuff, so just disabled the mesh instead.

If the collider you are aiming for is inside a child of another object with colider, it will always hit the parent collider (as fas as I observed)

The problem for me was that I had a boundary object used to destroy objects. It was invisible so I didn’t know the raycast was hitting it first.

The solution is to add the boundary object to the ‘Ignore Raycast’ layer.

Simple as that.

Found the solution for this problem, (In my case)
Delete the Rigidbody Component… (if you have one)

Check the camera position.
In case of 2D when i set the position of camera to 0,0,0 no mouse events were working.
the default camera had some default minute negative z like -0.4 which was necessary for the mouse events.,Make sure to check the camera position.
I was working with 2D and i set the camera position to 0,0,0 and that was the reason no mouse events were working. When i created the default camera it had some minute negative z value like -0.4.

I’m having the same problem, got a collider attached to it, tried the very handy bit of debug code from Robertbu(OnMouseDown not firing? - #5 by robertbu) shown above, which shows the raycast is hitting the correct collider, but the OnMouseDown() just isn’t triggering. Tried deleting the prefab and creating it anew. Checked all the colliders in the scene, none are in the way. I’ve set everything else in the scene to the ignore raycast layer, there literally is nothing else for the raycast to hit. Nothing seems to work…

The solution to all:
guys, if you have NO Update() handler the OnMouseDown() handler wo’t be fired.

Solution:
Just add an empty oid Update(){} function

I have a similar problem in a cube whitout a collider, thought.
Here is my snippet:

#pragma strict

//1 var to track the rotation state and speed
var rotationState: boolean = true;
var rotationSpeed: float = 20;


function Start () {
// changes the shader color at runtime
transform.renderer.material.color = Color.red;

}

function Update () {

	if (rotationState == true){
		transform.Rotate (0, rotationSpeed * Time.deltaTime, 0);
	}

}

//2
function onMouseDown() {
	if (rotationState == true){
		rotationState = false;
	}else if(rotationState == false){
		rotationState = true;
	}
	
	print ("Rotation State =" + rotationState);

}