Raycast from scene camera - how to make it work in prefab mode

Hi,

I have this neat little script that allows me to do CTRL+T to snap an object to the raycasted location at the mouse position on screen in my scene.

It’s not working in prefab mode, and I’d like to make it work. Any idea?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;

public class OUTBRKShortcuts : MonoBehaviour
{
    private static bool isMoving;

    [MenuItem("Tools/OUTBRK/Snap Object To Mouse Position %t")]
    static void SnapObjectToMousePosition()
    {
        isMoving = true;

        SceneView.duringSceneGui -= UpdateSceneView;
        SceneView.duringSceneGui += UpdateSceneView;
    }

    private static void UpdateSceneView(SceneView sceneView)
    {
        if (isMoving)
        {

            Vector3 pointPos = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin;
            Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
           
            RaycastHit hitInfo;

            if (Physics.Raycast(worldRay, out hitInfo, 10000))
            {
                if(hitInfo.collider.gameObject != null)
                {
                        // Move Selected Objects to raycast hit
                        if (Selection.gameObjects.Length > 0)
                        {
                            foreach (GameObject go in Selection.gameObjects)
                            {
                                Undo.RecordObject(go.transform, "Move Object to Mouse Position");
                                go.transform.position = hitInfo.point;
                            }
                            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
                        }
                }
            }

            EditorWindow view = EditorWindow.GetWindow<SceneView>();
            view.Repaint();

            isMoving = false;
        }
        else
        {
            SceneView.duringSceneGui -= UpdateSceneView;
        }
    }
}

Thanks!

I just had a similar problem and HAD to put the prefab in a scene, do the raycast operations there and save the changes on the prefab from there. Seems like Raycasts (of various types, at least Physics.Raycast and Physics.RaycastAll) do not work on prefab mode

1 Like