raycast mouse position unity code example

Example 1: unity ray from mouse position

RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit)) {
  Transform objectHit = hit.transform;

  // Do something with the object that was hit by the raycast.
}

Example 2: unity 2d raycast mouse

// detect object that was clicked using raycast

RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
 
if(hit.collider != null)
{
    Debug.Log ("Target name: " + hit.collider.name);
}

Example 3: mouse click unity raycast unity

if ( Input.GetMouseButtonDown (0)){ 
   RaycastHit hit; 
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
   if ( Physics.Raycast (ray,out hit,100.0f)) {
     StartCoroutine(ScaleMe(hit.transform));
     Debug.Log("You selected the " + hit.transform.name); // ensure you picked right object
   }
 }