(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.

Is Trigger is not necessary...that's only if you want the collider to behave like a trigger, and has no effect on OnMouseDown. @radlemur: I put the script on a cube in the setup you describe and it works as expected.

–

I tried this in a fresh project and it worked fine. Still not working in the original project. I wonder what else could be causing it to not register...

–

I doubt it, this was initially a particle system with a sphere collider and then switched to a new scene in the same existing project that only had the camera and the cube. Maybe it's something at the project level. I have since switched to using plain Raycast, but will leave this open as I'm curious what other reasons could there be for the click to not register...

–

I had the same problem. It turned out that the test cube was a child of another object. (I make a ship moving and the cube was on the ship). When I place the cube at the root of the scene, it worked. Not sure this is of any help to you, though, since you say starting from an empty scene. Good luck

–

We have the same problem with a much larger project. OnMouseDown has just stopped working. It's not a code change we have done, because we went back to a backup where OnMouseDown works and then brought its code version up to the latest i.e. the same as the one with the problem, and the problem does not occur. Seems to be something at the project level. No clue what though, or even where to start looking for it.

–

18 Answers

18

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 ("--------------");
		 	}
		}
	}
}

Collider might be missing in this case. Add collider to the cube and try.

–

You need to add a collider to your cube, it's necessary to use OnMouseDown And the function name is OnMouseDown and not onMouseDown ZeroKcm

–

Sweet, thank you so much for the code block above. Couldn't figure out why something wasn't working and this was the solution. Discovered I had moved an unrelated collider over another ... ugh. Thanks again!!!

–

Thanks man, the code helped me identify exactly why I kept failing to get OnMouseDown() to work.

–

This is such an awesome debugging tool. This helped me find my problem in a minute after over an hour of searching through the forums. Note: This uses the "old" input system. You need to make sure that's enabled to get this to fire.

–

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.

Also, it won't work if you are clicking on something that is not seen by the main camera.

–

@vividhelix I tried what you said and it worked! I just moved my objects a little closer to camera and the OnMouseDown() function responded. Thanks a bunch!

–

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

I too had a similar issue. I had a game object with a script using OnMouseDown that worked fine in one scene. I pulled it out from the scene as a prefab, saved, opened another scene and added it. OnMouseDown just wouldn't work. After trying everything else suggested in this post, I deleted the imported game object from the new scene, saved, closed Unity, re-opened the scene, added back my prefab and it worked.

–

Yes, I just fixed this issue with a image plane I was using as a button and I moved the image or object closer to the camera and shrunk it to fit the size I wanted on screen and it worked. onMouseDown only fires if the object is close enough to the camera.

–

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.,

I have the same issue, and working on a 2D project, I am using a 2D Colider, It has no Z axis to configure obviously and "It Triggers" is enabled, I have set all objects to position z=0 and the camera to z=1, still dont get OnMouseDown() to work...

–

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

Hi @MedalOfMode that will not do what we want to do, that code will be called whenever the mouse click anywhere on the screen, not specifically on the GameObject that the script belong to.

–

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.

hey, it is not working when I am using root motion. The colliders are moving with bone, but it is not colliding with any anything. The collisions are getting ignored on putting the colliders on child objects like the bones.

–

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

That's incorrect. There's no need for any Update function. OnMouseDown works fine without it.

–

Sorry guys, I added an update handler, restarted the scene and assumed that the fix was the added Update handler. We encountered this problem many times in different Unity versions now and all that fixes it is restarting Unity or re-opening the scene.

–

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);

}

@musicartslao You need to add a collider to your cube, it's necessary to use OnMouseDown And the function name is OnMouseDown and not onMouseDown ZeroKcm

–

No colliders ! I found the error in the update function: function Update () { if (rotationState){ transform.Rotate (0, rotationSpeed * Time.deltaTime, 0); } This works nicely !

–

I don't understand your solution... What do you change?

–