Home>

I want to get the object where I clicked with the mouse.

I tried to use the code below to skip Ray and get the object that hit Ray, but I can't get it.
I intended to get the object on the Scene clicked with the mouse and output it to the log, but the object different from the one at the clicked location is output.

Specifically, the screen of the game now looks like this image.

Even if I click on a tree or rock object with the mouse, the character object in the center of the screen is output for some reason.
Of course, Collider is attached to objects such as trees and rocks.
However, no matter how much you click on trees, rocks, or the ground, the character in the middle will be output to the log.

And there is a joystick at the bottom left of the screen and a button at the bottom right, but only when you click an object through these UIs (when you click the UI), the object over the UI is output.

This is my first time using Ray and I don't know what causes this behavior.
If anyone knows the cause, please let me know.
I visualized Ray, and it stretched firmly toward the mouse pointer.

Corresponding source code
void LateUpdate ()
{
            Raycast Hit hit;
            Ray ray = mainCamera.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit, 10))
            {
                if (Input.GetMouseButtonDown (0))
                {
                    Debug.Log (hit.collider.gameObject);
                }
            }
            Debug.DrawRay (ray.origin, ray.direction * 10, Color.red, 0.5f, false);
}
What I tried

Please describe here what you have tried for the problem.

Supplementary information (FW/tool version, etc.)

Please provide more detailed information here.

  • Answer # 1

    Ray's distance is short (it doesn't reach the back), so I think it's a good idea to extend it a little further.
    After that, I think that the order of shooting Ray when the mouse is clicked is correct, so I think that the processing order is reversed.

      void LateUpdate () {
            if (Input.GetMouseButtonDown (0)) {
                Raycast Hit hit;
                Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
                Debug.DrawRay (ray.origin, ray.direction * 100, Color.red, 0.5f, false);
                if (Physics.Raycast (ray, out hit, 100)) {
                    Debug.Log (hit.collider.gameObject);
                }
            }
        }

    In my environment, I can log with this, but what about?