unity3d 简单拖拽交换对象,类似背包物品交换功能

直接挂载到需要拖拽的每个对象上就可以了

unity3d 简单拖拽交换对象,类似背包物品交换功能_第1张图片
图片.png
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class OnTestDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private Vector3 beginPos;
    private Image image;
    void Start()
    {
        beginPos = transform.position;
        image = transform.GetComponent();
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
        image.raycastTarget = false;
        beginPos = transform.position;
        transform.SetAsLastSibling();
   }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition;
        transform.localScale = new Vector3(0.8f, 0.8f, 0.8f);
        OnTestDrag drag = eventData.pointerEnter.GetComponent();
        if (drag != null && drag.transform != transform)
        {
            transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        OnTestDrag drag = eventData.pointerEnter.GetComponent();
        if (drag != null && drag.transform != transform)
        {
            Vector3 pos = drag.transform.position;
            drag.transform.position = beginPos;
            transform.position = pos;
            transform.localScale = Vector3.one;
        }
        else
        {
            transform.position = beginPos;
            transform.localScale = Vector3.one;

        }
        image.raycastTarget = true;
    }

}

你可能感兴趣的:(unity3d 简单拖拽交换对象,类似背包物品交换功能)