參考
Unity Editor 實現給屬性面板上拖拽賦值資源路徑
API
Event
DragAndDrop
示例
Mono腳本
using UnityEngine;
public class TestScene : MonoBehaviour
{[SerializeField] string testName;
}
Editor腳本
重寫InspectorGUI,在該函數中通過Event的Type參數獲取當前的拖拽類型
拖拽中,如果鼠標指針進入目標區域,修改鼠標指針
拖拽釋放,判斷鼠標是否在目標區域,如果是,獲取拖拽內容的路徑
注意:不設置鼠標指針為通用狀態無法獲取拖拽對象的路徑
using UnityEditor;
[CustomEditor(typeof(TestScene))]
public class TestSceneInspector : Editor
{SerializedProperty testName;private void OnEnable(){testName = serializedObject.FindProperty(nameof(testName));}public override void OnInspectorGUI(){serializedObject.Update();EditorGUILayout.PropertyField(testName, new GUIContent("測試"));if (GetDragObjectPathsInProjectWindow(GUILayoutUtility.GetLastRect(), out string[] paths)){if (paths.Length > 0)testName.stringValue = System.IO.Path.GetFileNameWithoutExtension(paths[0]);}serializedObject.ApplyModifiedProperties();}bool GetDragObjectPathsInProjectWindow(Rect targetRect, out string[] paths){//拖拽提示if (Event.current.type == EventType.DragUpdated){Event.current.Use();if (DragObjectInArea(targetRect))DragAndDrop.visualMode = DragAndDropVisualMode.Generic;//鼠標指針修改為通用拖拽模式,設置為該模式該可以獲取拖拽對象的路徑elseDragAndDrop.visualMode = DragAndDropVisualMode.None;//鼠標指針修改為無指示模式 }//拖拽釋放并且在目標區域內if (Event.current.type == EventType.DragPerform && DragObjectInArea(targetRect)){Event.current.Use();paths = DragAndDrop.paths;return true;}else{paths = null;return false;}bool DragObjectInArea(Rect rect){return rect.Contains(Event.current.mousePosition);}}
}