1. 程式人生 > >Unity之DragAndDrop編輯器下拖拽區域

Unity之DragAndDrop編輯器下拖拽區域

在Inspector 視窗上建立區域,向區域拖拽資源物件,獲取到拖拽到區域的物件。

using UnityEngine;
using System.Collections;

public class Car : MonoBehaviour {
    [SerializeField]
    private Transform temp = null;

}
using UnityEngine;
using System.Collections;
using UnityEditor;

[CanEditMultipleObjects]
[CustomEditor(typeof(Car))]
public
class CarEditor : Editor { private SerializedProperty tempProperty; private UnityEngine.Object tempObj = null; void OnEnable() { tempProperty = serializedObject.FindProperty ("temp"); } public override void OnInspectorGUI () { serializedObject.Update(); GUILayout.Space (10
); tempObj = DragAreaGetObject.GetOjbect (); if (tempObj != null) { tempProperty.objectReferenceValue = tempObj; Debug.LogError(tempProperty.objectReferenceValue.name); } GUILayout.Space (10); if (GUI.changed) { EditorUtility.SetDirty(target); } serializedObject.ApplyModifiedProperties (); } }
using UnityEngine;
using System.Collections;
using UnityEditor;

public class DragAreaGetObject : Editor {

    public static UnityEngine.Object GetOjbect(string meg = null)
    {
        Event aEvent;
        aEvent = Event.current;

        GUI.contentColor = Color.white;
        UnityEngine.Object temp = null;

        var dragArea = GUILayoutUtility.GetRect (0f, 35f, GUILayout.ExpandWidth(true));

        GUIContent title = new GUIContent (meg);
        if (string.IsNullOrEmpty (meg)) 
        {
            title = new GUIContent("Drag Object here from Project view to get the object");
        }

        GUI.Box (dragArea, title);
        switch (aEvent.type)
        {
        case EventType.dragUpdated:
        case EventType.dragPerform:
            if (!dragArea.Contains(aEvent.mousePosition))
            {
                break;
            }

            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
            if (aEvent.type == EventType.DragPerform)
            {
                DragAndDrop.AcceptDrag();

                for (int i = 0; i < DragAndDrop.objectReferences.Length; ++i)
                {
                    temp = DragAndDrop.objectReferences[i];

                    if (temp == null)
                    {
                        break;
                    }
                }
            }

            Event.current.Use();
            break;
        default:
            break;
        }

        return temp;
    }
}

建立空物件,將Car.cs 掛在物件上,檢視如下
這裡寫圖片描述

拖拽資源到 Drag 區域內,將獲取到該資源