【Unity】在Scene窗口中发射射线
Handles
类中有很多用于在Scene中绘制形状的方法,HandleUtility
类中有很多处理Editor事件的方法,二者结合可以做出许多非常有用的编辑器扩展工具。例如,可以实现在Scene窗口中做射线检测。
在自定义脚本扩展中实现Scene射线
using UnityEngine;
using UnityEditor;
// 自定义脚本扩展中实现Scene射线
[CustomEditor(typeof(MyScript))]
public class CustomScriptEditor : Editor
{
private void OnSceneGUI()
{
Event currentEvent = Event.current;
if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
{
Ray ray = HandleUtility.GUIPointToWorldRay(currentEvent.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.LogError(hit.collider.name);
}
}
}
}
在自定义编辑器窗口中实现Scene射线
using UnityEngine;
using UnityEditor;
// 自定义编辑器窗口中实现Scene射线
public class CustomWindow : EditorWindow
{
private void OnEnable()
{
SceneView.duringSceneGui -= OnSceneGUI;
SceneView.duringSceneGui += OnSceneGUI;
//SceneView.onSceneGUIDelegate -= OnSceneGUI;
//SceneView.onSceneGUIDelegate += OnSceneGUI;
}
private void OnDestroy()
{
SceneView.duringSceneGui -= OnSceneGUI;
//SceneView.onSceneGUIDelegate -= OnSceneGUI;
}
private void OnSceneGUI(SceneView sceneView)
{
Event currentEvent = Event.current;
if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
{
Ray ray = HandleUtility.GUIPointToWorldRay(currentEvent.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.LogError(hit.collider.name);
}
}
}
}