ugui拖拽

整理了下以前写的

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(CanvasGroup))]
public class ItemDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
    private CanvasGroup canvasGroup;
    private Transform originalGrid;//拖出的格子
    public GameObject bagFrame;//拖出格子的父级
    Vector2 originGridSize;//原始大小
    
    // Start is called before the first frame update
    void Start()
    {
        originGridSize = (transform as RectTransform).sizeDelta;
        canvasGroup = GetComponent();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        //让eventTrigger无法检测到物体,让他去检测物体后面的格子
        canvasGroup.blocksRaycasts = false;
        originalGrid = gameObject.transform.parent;
        gameObject.transform.SetAsLastSibling();//设置ui最上层
    }

    public void OnDrag(PointerEventData eventData)
    {
        //把物体设置到背景上的字节点上,是为了防止格子挡住物品
        transform.SetParent(bagFrame.transform);
        //跟随鼠标移动
        transform.position = Input.mousePosition;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        //结束拖拽时,鼠标所碰撞的点的物品
        GameObject curEnter = eventData.pointerEnter;
        //满足条件,正确地放入格子里面
        if (curEnter != null && curEnter.tag == "bagGrid")
        {
            //设置格子的父节点
            transform.SetParent(curEnter.transform, false);
            //设置预制物的位置
            (transform as RectTransform).localPosition = Vector3.zero;
            (transform as RectTransform).localRotation = Quaternion.identity;
            (transform as RectTransform).localScale = Vector3.one;
            //设置成原来的大小
            (transform as RectTransform).sizeDelta = originGridSize;
        }
        //没有满足条件
        else
        {
            //设置格子的父节点
            transform.SetParent(originalGrid.transform);
            //设置预制物的位置
            (transform as RectTransform).localPosition = Vector3.zero;
            (transform as RectTransform).localRotation = Quaternion.identity;
            (transform as RectTransform).localScale = Vector3.one;
            //设置成原来的大小
            (transform as RectTransform).sizeDelta = originGridSize;
            print("没有满足条件");
        }

        //eventTrigger可以检测到物体
        canvasGroup.blocksRaycasts = true;
    }

    //点击
    public void OnPointerClick(PointerEventData eventData)
    {
        print("点击");
    }

    //鼠标进入
    public void OnPointerEnter(PointerEventData eventData)
    {
        print("进入");
    }

    //鼠标退出
    public void OnPointerExit(PointerEventData eventData)
    {
        print("退出");
    }
}

 

你可能感兴趣的:(ugui拖拽)