Unity3D – GetMouseButton – PhysicRaycast – Get GameObject tag

Once you have determined that your raycast actually hit something, you can query the name of your ‘hit’ object.

Create a scene with:

– Cube, tag it ‘Player’

– Main Camera, attach the script:


#pragma strict


function Update(){
    // if you press Mouse Button
    if (Input.GetMouseButtonDown(0)){ // if you press Left Mouse Button -> 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 MyObjectTag = hit.collider.tag; // get the tag of the 'hit' object
            
            Debug.Log(MyObjectTag); // the name of the clicked object
            // Do something...
        }
    }
 
}

Play, if you click the Cube you will see inside console ‘Player’.