Unity简单的拖拽放置UI

一、拖拽UI

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragDrop : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler
{
    private RectTransform thisrectTransform;
    public Canvas _Canvas;
    private CanvasGroup thisCanvasGroup;
    void Start()
    {
        thisrectTransform = GetComponent<RectTransform>();
        thisCanvasGroup = GetComponent<CanvasGroup>();
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
       // Debug.Log("开始拖拽");
        thisCanvasGroup.alpha = 0.6f;
        thisCanvasGroup.blocksRaycasts = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
       // Debug.Log("拖拽");
        thisrectTransform.anchoredPosition += eventData.delta/ _Canvas.scaleFactor;

    }

    public void OnEndDrag(PointerEventData eventData)
    {
        //Debug.Log("拖拽结束");
        thisCanvasGroup.alpha = 1;
        thisCanvasGroup.blocksRaycasts = true;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        //Debug.Log("按下");
    }  
}

二、放置

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ItemSlot : MonoBehaviour, IDropHandler
{

    public void OnDrop(PointerEventData eventData)
    {
        if (eventData.pointerDrag != null)
        {
           eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition=GetComponent<RectTransform>().anchoredPosition; 
         
        }
    }
}

三、
在这里插入图片描述
在这里插入图片描述


版权声明:本文为qiao2037641855原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。