I’m writing an editor script to position objects, and trying to cast a ray straight forward from the center of the editor viewport. It seems relatively straightforward, I just divide the screen dimensions by half and cast from the viewport:
Vector3 centerOfCamera = new Vector3(Screen.width / 2, Screen.height / 2, 0);
Ray ray = SceneView.lastActiveSceneView.camera.ViewportPointToRay(centerOfCamera);
However, this doesn’t work- casting forward never returns a hit, even when the camera is directly facing a nearby collider or mesh surface, and Debug.DrawRay never produces a visible debug line anywhere. I assume my math is wrong, but this seems really straightforward- did I miss a conversion somewhere?
Maybe the camera center is not on z = 0 and you are casting ray from behind the object.
You confused ScreenSpace with ViewportSpace.
ScreenSpace goes from bottom-left (0, 0) to top-right (Screen.width, Screen.height)
ViewportSpace goes from bottom-left (0, 0) to top-right (1, 1)
You are passing Screen space coordinates to a method that expects viewport space coordinates.
The center of the viewport is just
SceneView.lastActiveSceneView.camera.ViewportPointToRay(new Vector3(0.5f, 0.5f));
However you rarely want to use the sceneview camera like this. What exactly are you trying to do here? Anything related to the sceneview usually involves the Handles and HandleUtility classes. However without more details on the problem we can’t suggest anything. Keep in mind that you can have more than one sceneview open at the same time. Any user interaction with a sceneview should be done in the callback of that specific sceneview.