该功能演示了拖拽场景中的物体到编辑器界面。并显示物体完整路径
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class OpenWindow : EditorWindow
{
string path;
[MenuItem("Tools/Open")]
static void Open()
{
GetWindow<OpenWindow>();
}
private void OnGUI()
{
GUILayout.BeginHorizontal();
GUILayout.Label("Path");
path=GUILayout.TextField(path);
GameObject obj = GetDragGameObjectFromScene(GUILayoutUtility.GetLastRect());
if (obj!=null)
{
path = GetObjectScenePath(obj);
}
GUILayout.EndHorizontal();
}
public static GameObject GetDragGameObjectFromScene(Rect r)
{
Event e = Event.current;
if (e.type == EventType.DragUpdated || e.type == EventType.DragPerform)
{
Object dragObject = DragAndDrop.objectReferences[0];
if (dragObject is GameObject)
{
if (PrefabUtility.GetCorrespondingObjectFromSource(dragObject) == null && PrefabUtility.GetPrefabInstanceHandle(dragObject) != null)
{
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
}
else
{
if (r.Contains(e.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Link;
if (e.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
return dragObject as GameObject;
}
e.Use();
}
}
}
else
{
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
}
}
return null;
}
public static string GetObjectScenePath(GameObject o)
{
string result = AssetDatabase.GetAssetPath(o);
if (!string.IsNullOrEmpty(result))
{
return result;
}
Transform t = o.transform;
string path = t.name;
while (t.parent != null)
{
path = t.parent.name + "/" + path;
t = t.parent;
}
return path;
}
}