UGUI拖拽和放下物品

1.让脚本同时继承MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler这几个类

2.OnBeginDragHandler()是开始拖动时调用。为了使要拖动的ui不被遮挡,先把它的层级改一下,父物体改为Canvas。并且把raycastTarget设为false,为了放下时能检测到该放下的位置。

public void OnBeginDrag(PointerEventData eventData)
    {
     
        transform.SetParent(UIRoot);//暂时改变渲染层级
        GetComponent<Image>().raycastTarget = false;
    }

3.OnDrag()里面让该物体跟着鼠标位置移动

public void OnDrag(PointerEventData eventData)
    {
      
        transform.position = eventData.position;
    }

4.OnEndDrag()里将该ui的父物体设为鼠标松开时的物体,并设置localposition,同时恢复raycastTarget以便下次拖拽。

public void OnEndDrag(PointerEventData eventData)
    {
     
    	//获取松开停止拖拽时位于鼠标位置的物体
        GameObject go = eventData.pointerCurrentRaycast.gameObject;
        //print(go.tag);
        //这里根据tag来判断拖动是否有效
        if (go!=null&&go.tag == Tags.inventoryItemGrid)
        {
     
            transform.SetParent(go.transform);
            transform.localPosition = Vector3.zero;
        }
        else
        {
     
            transform.SetParent(preParent);
            transform.localPosition = Vector3.zero;
        }
        GetComponent<Image>().raycastTarget = true;
    }

完整代码:

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

public class InventoryItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler{
     
    public Transform UIRoot;//Canvas
    public Transform preParent;//原来的父物体

    private void Awake()
    {
     
        UIRoot = GameObject.Find("UI Root").transform;
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
     
    	preParent = transform.parent;//保存原来的父物体
        transform.SetParent(UIRoot);//暂时改变渲染层级
        GetComponent<Image>().raycastTarget = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
      
        transform.position = eventData.position;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
     
        GameObject go = eventData.pointerCurrentRaycast.gameObject;
        //print(go.tag);
        if (go!=null&&go.tag == Tags.inventoryItemGrid)
        {
     
            transform.SetParent(go.transform);
            transform.localPosition = Vector3.zero;
        }
        else
        {
     
            transform.SetParent(preParent);
            transform.localPosition = Vector3.zero;
        }
        GetComponent<Image>().raycastTarget = true;
    }
}

效果:
UGUI拖拽和放下物品_第1张图片
UGUI拖拽和放下物品_第2张图片
UGUI拖拽和放下物品_第3张图片

你可能感兴趣的:(Unity&游戏设计,unity3d,拖拽,背包,ugui)