OnMouseDown() not firing, even though attached to collider under mouse.
I have a game object with a component attached with this code:
void OnMouseDown()
{
Debug.Log("Mouse down");
}
Clicking on it in the game does nothing. So I created a test component that does a raycast from the mouse, lists the colliders it hits, and sends those colliders a "OnMouseDown" message when I press F1:
void Update()
{
if (Input.GetKeyDown(KeyCode.F1))
{
ListRaycasts();
}
}
private void ListRaycasts()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits;
hits = Physics.RaycastAll(ray);
int i = 0;
while (i < hits.Length)
{
RaycastHit hit = hits[i];
Debug.Log(hit.collider.gameObject.name);
hit.collider.gameObject.SendMessage("OnMouseDown");
i++;
}
}
When I press F1 while over the object, I see the object listed and its OnMouseDown method fires. Why doesn't it fire when I click?
Answer by Naphier · Apr 19, 2016 at 10:39 PM
Is it set to be a trigger?
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
This function is not called on objects that belong to Ignore Raycast layer. This function is called on Colliders marked as Trigger if and only if Physics.queriesHitTriggers is true.
No. 1 reason that On$$anonymous$$ouseDown doesn't work ;)
Wait, so colliders have to be triggers to get the event? That seems the opposite of what the docs say "This function is called on Colliders marked as Trigger if and only if Physics.queriesHitTriggers is true."
Your answer
Follow this Question
Related Questions
Why are my wheel colliders making a wheelie? 1 Answer
Pick Up and Drop Script not functioning due to loophole 1 Answer
Unity 5 Target Star wheel arm physics 0 Answers
How to ensure raycasts hit colliders inside of trigger colliders on objects that have a rigidbody? 0 Answers
Strange physics on RigidBody when Collider enabled (locked axis) 2 Answers