unity know when gameobject presed 1

unity know when gameobject presed

void Update () {
         if (Input.GetMouseButtonDown(0)) {
             CastRay();
         }       
     }

     void CastRay() {
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
         if (hit.collider !=null) {
             Debug.Log (hit.collider.gameObject.name);
     }

Here is what the above code is Doing:
1. We create a Ray object, which is a line that starts at the camera and goes into the scene.
2. We create a RaycastHit2D object, which will store information about what the ray hit.
3. We use the Physics2D.Raycast() method to cast the ray and store the information in hit.
4. We check if the ray hit something.
5. If it did, we print the name of the object it hit.

Similar Posts