Unity3D Game Engine – Get Mouse Button – Physic.Raycast – Hit GameObject

Physic.Raycast is useful if you need to know the exact point where the mouse pointer is.

Create a scene with:

– Main Camera
– Cube
– Empty Object, assign GetMouseClick.js:


#pragma strict

function Update(){
    // if you press Left Mouse Button -> GetMouseButtonDown(0) 
    if (Input.GetMouseButtonDown(0)){
        var hit: RaycastHit;
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition); // it sends a ray from Camera.main
        if (Physics.Raycast(ray, hit)){ // if it hits something        

            var object = hit.transform.gameObject; // if the ray hits a GameObject
 
            Debug.Log("Clicked!");
            // Do something...
        }
    }
 
}

Play and click over the Cube

NOTICE: You can assign the script at every object in the scene