Unity3D – GetMouseButton – PhysicRaycast – Get GameObject name
Once you have determined that your raycast actually hit something, you can query the name of your ‘hit’ object.
Create a scene with:
– Cube, remame myCube
– 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 MyObjectName = hit.collider.gameObject.name; // get the name of the 'hit' object Debug.Log(MyObjectName); // show the name of the clicked object // Do something... } } }
Play, if you click the Cube you will see inside console ‘myCube’.