unity 编辑器二次开发,在非运行状态下,在scene场景点击某个物体出现一条线,起始点是该物体,终点在鼠标位置,当鼠标点击其他球体后线的终点放到最后被点击的物体上
时间: 2023-11-20 17:05:21 浏览: 125
Unity实现移动物体到鼠标点击位置
这个功能可以通过编写Unity Editor插件来实现。以下是一个示例脚本,可以实现在非运行状态下,点击场景中的物体出现一条线,并且当鼠标点击其他物体时,线的终点会自动切换到最后被点击的物体上。
```csharp
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class SceneClickHandler : EditorWindow
{
private static SceneClickHandler _instance;
private GameObject _startObject;
private GameObject _endObject;
private Vector3 _mousePosition;
static SceneClickHandler()
{
SceneView.duringSceneGui += OnSceneGUI;
}
[MenuItem("Custom/Scene Click Handler")]
public static void ShowWindow()
{
_instance = GetWindow<SceneClickHandler>();
_instance.titleContent = new GUIContent("Scene Click Handler");
}
private static void OnSceneGUI(SceneView sceneView)
{
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (_instance._startObject == null)
{
_instance._startObject = hit.collider.gameObject;
_instance._endObject = null;
}
else if (_instance._endObject == null || _instance._endObject != hit.collider.gameObject)
{
_instance._endObject = hit.collider.gameObject;
}
}
}
else if (Event.current.type == EventType.MouseMove)
{
_instance._mousePosition = Event.current.mousePosition;
SceneView.RepaintAll();
}
if (_instance._startObject != null)
{
Handles.DrawLine(_instance._startObject.transform.position, _instance._mousePosition);
if (_instance._endObject != null && _instance._endObject != _instance._startObject)
{
Handles.DrawLine(_instance._startObject.transform.position, _instance._endObject.transform.position);
}
}
}
}
```
将以上代码保存为名为`SceneClickHandler.cs`的文件,然后将它放到`Assets/Editor`目录下。接着在Unity编辑器中选择`Custom/Scene Click Handler`菜单项,就可以打开插件窗口了。在非运行状态下,在场景中点击物体,就会出现一条线,并且当鼠标点击其他物体时,线的终点会自动切换到最后被点击的物体上。
阅读全文