Search Unity

How to get mouse click world position in the scene view in editor script (NOT BY RAYCAST)

Discussion in 'Editor & General Support' started by usernameHed, Jul 30, 2019.

  1. usernameHed

    usernameHed

    Joined:
    Apr 5, 2016
    Posts:
    93
    Hello, everything is on the title.

    When I am right clicking on the editor view, I want to create a world object at the position I am clicking.

    Yes, it work with a raycast:
    Code (CSharp):
    1. Vector2 mousePos = Event.current.mousePosition;
    2.  
    3. RaycastHit _saveRaycastHit;
    4. Ray worldRay = HandleUtility.GUIPointToWorldRay(mousePos);
    5.        
    6. if (Physics.Raycast(worldRay, out _saveRaycastHit, Mathf.Infinity))
    7.         {
    8.             if (_saveRaycastHit.collider.gameObject != null)
    9.             {
    10.                 //_saveRaycastHit.point;
    11.             }
    12.         }
    13. else
    14. {
    15.     //here How can I extrapolate a position ?
    16. }
    Here if my raycast work, that mean i touch an object, then I can have the position, OK.
    But if my raycast doen't touch anything, I want to extrapolate a world position anyway.

    How can I do that ?
    Thanks !
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,638
    just position your new object at worldRay.direction * (how far away you want it from the camera)

    Edit: Actually, what I wrote there is not quite right. The expression above would need to be added to a point in world space that corresponds to where you clicked. I think this should work:

    worldRay.location + (worldRay.direction * [how far away you want it from the camera]);
     
    Last edited: Jul 30, 2019
  3. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,436