Raycast doesn't go in the right direction

Hello ! I want to select a 3D Gameobject on mouse down using Raycast. I put the script on the Camera, but it does’nt work : it prints some gameObject name but not the one I touched with the mouse. It’s like the direction of the Raycast wasn’t to the mouse.
I try to use it in a very simple scene with juste a plane and a cube. What am I doing wrong ?

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("Mouse down");
            RaycastHit hit;
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                Transform objectHit = hit.transform;
                Debug.Log("Object selected : " + objectHit.gameObject.name);
            }
        }
        
    }

Hi!

I made this for you just quickly. I don’t have time to test it unless it doesn’t work for you.

void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hitInfo = new RaycastHit();
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo))
            {
                Debug.Log(hitInfo.collider.gameObject.name);
            }
            else
            {
                //whatever needs to be done here
                Debug.Log("No hit");
            }
        }
    }

Note: You need to have colliders (can be set as a trigger) on your objects! Otherwise, raycasts will go straight through them. Common error. Enjoy :slight_smile: