Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

(In EDITOR) Detecting mouse click position on a plane in world coords using RayCast from camera

Discussion in 'Immediate Mode GUI (IMGUI)' started by shosanna, Sep 27, 2016.

  1. shosanna

    shosanna

    Joined:
    Jun 25, 2016
    Posts:
    7
    Hello,

    I am trying to detect where I clicked (mouse position in the world) in order to instantiate objects, while in the scene editor. When I tried that in the game, it was very easy and it worked like a charm, here is the code:

    Code (CSharp):
    1. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    2. RaycastHit hit = new RaycastHit();
    3.  
    4. // This script is attached to the plane, so GetComponents returns the plane's collider
    5. if (GetComponent<Collider>().Raycast(ray, out hit, Mathf.Infinity)) {
    6.     // do stuff
    7. }
    8.      
    When I wanted this to work inside the editor, I moved my script to the editor folder, I put on the beginning of the class
    Code (csharp):
    1.  [CustomEditor(typeof(Transform))]
    (although I have no idea why did I put that it is a type of transform, I googled it and it just worke).

    The script is running in the editor, which I can tell it because it does stuff to the scene, it just doesn't calculate the mouse position correclty.

    The exact same code altered for the editor:

    Code (csharp):
    1.  
    2. Ray ray = SceneView.currentDrawingSceneView.camera.ScreenPointToRay(e.mousePosition);
    3. RaycastHit hit = new RaycastHit();
    4.  
    5. // Plane is found using GameObject.Find, so it should be the exact same instance as the one in the first case
    6. if (plane.GetComponent<Collider>().Raycast(ray, out hit, Mathf.Infinity)) {
    7.   // do stuff
    8. }
    9.  
    In both cases I am using plane as a "floor" against which I am casting the ray. In the editor version it places my objects in the scene, but in the wrong position. It seems to depend on which angle I have the editor / scene camera rotated, but I thought it would be already handled by the camera's ScreenPointToRay function.
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,271
    I've used something like this,
    Code (CSharp):
    1. Vector3 mouseWorld = Event.current.mousePosition;
    2. mouseWorld.y = SceneView.currentDrawingSceneView.camera.pixelHeight - mouseWorld.y;
    3. mouseWorld = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(mouseWorld);
    4. //mouseWorld.z = 0;
    5.