detecting a mousedown on gameobject - OnMouseDown or raycast?

Hello!

I am quite new to unity, so sorry for the dumb question. I want to detect a mousedown on a game object (more specifically, I would like to know how many seconds the mouse button was held over the game object, and the position on the collider the click was done on).

A quick googling showed that there is two ways to detect mousedown: OnMouseDown() and raycast. I don’t know which one is better or quicker. Which one should I use? With OnMouseDown, can I have the coordinates where the user clicked on?

Currently I made a solution where I detect mouseclick with OnMouseDown/OnMouseUp, and in OnMouseUp I do a raycast to acquire a normal on the collider.

Thanks for the help,
Eszter

OnMouseDown goes in the object script, while raycast may be in a script attached to anything. OnMouseDown is easier when you must detect if the object was clicked - but you don’t know exactly where. Since you need to know the exact point, you should use Physics.Raycast:

var point: Vector3;
var duration: float;
var object: GameObject;
private var startTime: float = 0;

function Update(){
    if (Input.GetMouseButtonDown(0)){
        var hit: RaycastHit;
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, hit)){
            startTime = Time.time;
            point = hit.point;
            object = hit.transform.gameObject;
        }
    }
    else 
    if (Input.GetMouseButtonUp(0)){
        duration = Time.time - startTime;
    }
}

This script may be attached to any object (usually Main Camera or an empty object). It will measure the click duration in duration and return the point in point and the clicked object in object