- Home /
How to raycast from mouse position in scene view?
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:
Press a button on the inspector of a script to start raycasting.
As user moving through scene it selects (keeps record of) all the objects that intersect with ray from current mouse position.
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
Answer by lgarczyn · Nov 21, 2019 at 11:02 PM
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?
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612215120im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycast doesn't work properly? 0 Answers
Surface with hole and Raycast - Which collider 1 Answer
Physics.Raycast to Physics2D.Raycast? 1 Answer
RayCast Nearest Character 0 Answers