How to Raycast from mouse position in Scene view?
Asked Answered
E

2

0

I’m trying to Raycast in scene view based mouse position. I pretty much want to mimic the unity’s behavior when you click some where it selects that objects except I wish to get all the objects through that ray.

Here’s exactly what I want to do:

  1. Press a button on the inspector of a script to start Raycasting.
  2. As user moving through scene it selects (keeps record of) all the objects that intersect with ray from current mouse position.
  3. Then user clicks in the scene view to stop the Raycasting and the last set of selected objects is shown in the inspector.

I’ve search and not seen a solution that works. It seems like such a trivial thing to be able to do.

So if anyone can create a simple script of function that works that would be great.

Here’s a link to what I have so far: https://gist.github.com/lordlycastle/fdc919da37585410309df3231ed03e00 (link is dead)

Euphony answered 3/10, 2023 at 11:21 Comment(0)
B
0

You need to write an editor script, specifically an EditorWindow most likely. There is a lot to learn about here, so I suggest reading more into them.

To get the direction and position of your raycast, you need this:

 Ray ray = SceneView.lastActiveSceneView.camera.ScreenPointToRay(Event.current.mousePosition);
 //or maybe
 Ray ray = HandleUtility.GUIPointToWorldRay (Event.current.mousePosition);

To do a raycast that returns all objects, you need RaycastAll

You can probably use Event to check for clicks, but not sure about that. Maybe create a new command bound to a script?

Broadnax answered 3/10, 2023 at 11:31 Comment(1)

Thanks for this. I used the first option until I noticed that the rays were very wrong on MacOS Editor 2019.4. The second version works well on all platforms I tested. And unlike the first line, the second one does not require flipping the y coordinate or accounting for an offset that the scene view toolbar introduces.

Viand
M
0

This code will Raycast mouse position against world XZ plane in Scene view:

#if UNITY_EDITOR
void OnDrawGizmos ()
{
    Vector2 mousePos = Event.current.mousePosition;// (0,0) is upper left
    mousePos *= UnityEditor.EditorGUIUtility.pixelsPerPoint;// OS display scale
    var camera = UnityEditor.SceneView.lastActiveSceneView.camera;
    Vector3 vec = new Vector3( mousePos.x , camera.pixelHeight-mousePos.y , 1 );// (0,0) is lower left
    Ray ray = camera.ScreenPointToRay( vec );
    if( new Plane(inNormal:Vector3.up,inPoint:Vector3.zero).Raycast(ray,out float dist) )
    {
        Vector3 hitPoint = ray.origin + ray.direction * dist;
        Gizmos.color = Color.yellow;
        Gizmos.DrawRay( hitPoint , Vector3.up );
    }
}
#endif

source: https://forum.unity.com/threads/mouse-position-in-scene-view.250399/#post-8067917

With special dedication to anyone lost in this cursed API yet again.

Maximin answered 3/10, 2023 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.