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 区域内,将获取到该资源

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值