Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to raycast from camera through mouse position?

Discussion in 'Scripting' started by EliteWalrus, Jan 27, 2015.

  1. EliteWalrus

    EliteWalrus

    Joined:
    Aug 16, 2014
    Posts:
    44
    This code
    Code (CSharp):
    1.         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    2.         if (Physics.Raycast (ray, out hit, 100)) {
    3.             Debug.Log (hit.transform.name);
    4.             Debug.Log ("hit");
    5.         }
    does nothing.
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    That code looks correct.

    Are you sure what you are trying to hit has a 3D collider and is within 100 units?
     
  3. lulutube14

    lulutube14

    Joined:
    Sep 16, 2020
    Posts:
    12
    You need a RaycastHit variable, like this:

    Code (CSharp):
    1. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    2.             RaycastHit hit;
    3.             if (Physics.Raycast(ray, out hit, 100))
    4.             {
    5.                 Debug.Log(hit.transform.name);
    6.                 Debug.Log("hit");
    7.             }
     
    Talmagett_Games likes this.
  4. MuratBingol

    MuratBingol

    Joined:
    May 20, 2021
    Posts:
    3
    If the object you are raycasting is more than 100 units away from the camera, the raycast will not work correctly..
    so either zoom the object to the camera or increase the maxdistance
     
  5. lipodilaces0510

    lipodilaces0510

    Joined:
    Jul 24, 2022
    Posts:
    1
    You can use Math.Infinity as the range, also answer #3 is correct, you need to create the Raycast Hit variable first.