Monday, December 10, 2012

Unity how to check which object you click using mouse

Here is what you should do if you wanna check which object you have clicked

function Update()
{
    //check if the left mouse has been pressed down this frame
    if (Input.GetMouseButtonDown(0))
    {
        //empty RaycastHit object which raycast puts the hit details into
        var hit : RaycastHit;
        //ray shooting out of the camera from where the mouse is
        var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, hit))
        {
            //print out the name if the raycast hits something
            Debug.Log(hit.collider.name);
        }
    }
}


Note: Make sure your object have box collider otherwise it wont be detected

No comments:

Post a Comment