UGUI(背包实现)

实现一个简单的背包功能(可以拖动物体,如果不属于有效范围会自动返回原来父物体的下面)


UGUI(背包实现)_第1张图片
图1-1最终效果图

布局格式

BagPackUI是一个panel控件

BagGrid:空物体

bag_bg:背景

Item:物体需添加图1-2所示组件(Canvas Group组件)

当Blacks Raycasts=false时射线可以检测到下一层物体为true是不可以检测下一层

UGUI(背包实现)_第2张图片
图1-2

布局层次如图1-3所示

UGUI(背包实现)_第3张图片
图1-3

实现代码

管理类

using UnityEngine;

using System.Collections;

public class BagPackMgr : MonoBehaviour{  

  //tag标签的常量字符串   

 public const string groove = "groove"; 

   public const string bagpackItem = "bagpackItem";  

  public const string bag = "bag";   

 Canvas GlobalCanvas;//画布  

  Transform BagGrid;//背包的道具父物体  

  //单件模式(单例模式)

    static BagPackMgr Inst; 

   public static BagPackMgr Instance    {    

    get        {        

    return Inst;    

    }    

}   

 void Awake()    {       

 Inst = this;       

GlobalCanvas = transform.parent.GetComponent();

BagGrid = transform.Find("BagGrid");

}

public Canvas getGlobalCanvas

{

get {

return GlobalCanvas;

}

}

public Transform GetBagGrid

{

get {

return BagGrid;

}

ItemDrag类

ItemDrag类

using UnityEngine;

using System.Collections;

using UnityEngine.EventSystems;

using System;

public class ItemDrag : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler {  

  Transform _saveSelfParent;//保存自己的父物体   

 CanvasGroup _canvasGroup;//CanvasGroup组件  

//鼠标点的那一帧执行

  public void OnBeginDrag(PointerEventData eventData)  

  {     

   _canvasGroup = GetComponent();

_canvasGroup.blocksRaycasts = false;//不阻挡向下检测控件

_saveSelfParent = transform.parent;//将该物体的父物体保存在_saveSelfParent中

//设置父物体为画布Canvas

transform.SetParent(BagPackMgr.Instance.getGlobalCanvas.transform);

}

//拖动的过程中执行

public void OnDrag(PointerEventData eventData)

{

transform.position = eventData.position;//当下的位置赋给该物体(物体随鼠标移动)

}

//拖动结束时执行

public void OnEndDrag(PointerEventData eventData)

{

GameObject pointEenterobj = eventData.pointerEnter;

//空白出或外面,非响应区域

if (pointEenterobj == null)

{

transform.SetParent(_saveSelfParent);

transform.localPosition = Vector3.zero;

}

//拖动到了装备栏

else if (pointEenterobj.tag == BagPackMgr.groove)

{

transform.SetParent(pointEenterobj.transform);

transform.localPosition = Vector3.zero;

}

//拖到了道具上(交换位置)

else if (pointEenterobj.tag == BagPackMgr.bagpackItem)

{

transform.SetParent(pointEenterobj.transform.parent);

transform.localPosition = Vector3.zero;

pointEenterobj.transform.SetParent(_saveSelfParent);

pointEenterobj.transform.localPosition = Vector3.zero;

}

//卸下道具

else if (pointEenterobj.tag == BagPackMgr.bag)

{

transform.SetParent(BagPackMgr.Instance.GetBagGrid);

transform.localPosition = Vector3.zero;

}

//射线检测到了物体,但是不是我们逻辑需要的三种类型(无效操作)

else

{

transform.SetParent(_saveSelfParent);

transform.localPosition = Vector3.zero;

}

//重置射线检测

_canvasGroup.blocksRaycasts = true;

}

你可能感兴趣的:(UGUI(背包实现))