使用Unity完成簡單的背包功能
用UGUI布局成一下這個樣子
設置BackGround的tag為Bag?
Lft,Center,Right設置為Groove
所有的Item設置為BagItem
在BackGround中添加組件Grid Layout Group,使拖動上去之后能夠正確排版
并且為所有item添加CanvasGroup組件,當BlockRaycasts為false時使射線能夠穿透該物體,反則則不能
編寫腳本
在BackGround上掛載的腳本.m_BagPageMgr,這是一個管理類
using UnityEngine;
public class m_BagPageMgr : MonoBehaviour
{? ??
Transform _Panle; ? //保存Panle的Transform?
Transform BackGound; ? ?//保存BackGround的Transform
void Awake()? ??
{? ? ? ??
_Panle = transform.parent.GetComponent<Transform>(); ? ? ? //獲取到Transform組件
BackGound = GetComponent<Transform>();//獲取到Transform組件
Inst = this;//初始化實例
}
private m_BagPageMgr()//私有化構造方法,使外部不能隨意實例化該類
{
}
static m_BagPageMgr Inst;//定義一個靜態的私有的實例
public static m_BagPageMgr Instance//使用屬性獲取上面的實例
{
get
{
return Inst;
}
}
public? Transform getPanle//使用屬性獲取Panle的Transform
{
get
{
return _Panle;
}
}
public Transform getBG//使用屬性獲取BackGround的Transform
{
get
{
return BackGound;
}
}
}
在Item上掛載的組件
using UnityEngine;
using UnityEngine.EventSystems;
public class m_ItemDarg : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler//繼承能夠實現拖拽的接口
{? ??
CanvasGroup _canvasGroup;? ? //定義一個CanvasGroup的引用變量
Transform _selfParent; ? ?//這個用來保存當前的父對象
void Awake()? ??
{? ? ? ??
_canvasGroup = transform.GetComponent();//獲取Item上的CanvasGroup組件
}
public void OnBeginDrag(PointerEventData eventData)//當開始拖動時調用該方法,且只調用一次
{
_selfParent = transform.parent;//記錄下當前對象的父物體
_canvasGroup.blocksRaycasts = false;//使射線能夠穿過鼠標拖拽的物體
transform.SetParent(m_BagPageMgr.Instance.getPanle.transform);//當鼠標開始拖拽時,將其父物體設置為Panle,使其能夠顯示在在所有的游戲對象上面
}
public void OnDrag(PointerEventData eventData)//當鼠標正在拖動時調用,在這期間該方法一直調用
{
transform.position = eventData.position;//使鼠標拖拽的物體的位置等于鼠標的位置
}
public void OnEndDrag(PointerEventData eventData)//當鼠標拖拽完成,松開鼠標時執行該方法,且只執行一次
{
GameObject pointobj = eventData.pointerEnter;//獲取鼠標拖拽的物體下面的游戲對象
if (pointobj == null)//當該游戲對象為空時
{
transform.SetParent(_selfParent);//將其返回至原來的位置,也就是將其父對象設置成初始的父對象
transform.localPosition = Vector3.zero;//坐標歸零
}
else if (pointobj.tag == "Bag")//當射線檢測到的是BackGround時
{
transform.SetParent(m_BagPageMgr.Instance.getBG.transform);//將其父物體設置為BackGround
transform.localPosition = Vector3.zero;
}
else if (pointobj.tag == "Groove")//當射線檢測到的是Lft,Center,Right,這三個的時候
{
transform.SetParent(pointobj.transform);//將該物體的父物體設置為檢測到的物體
transform.localPosition = Vector3.zero;
}
else if (pointobj.tag == "BagItem")//當射線檢測到的是Item時,交換兩個的父物體
{
transform.SetParent(pointobj.transform.parent);
transform.localPosition = Vector3.zero;
pointobj.transform.SetParent(_selfParent);
pointobj.transform.localPosition = Vector3.zero;
}
else//以上都不滿足時,這是我們并不期望的一個結果,所以返回初始的父對象
{
transform.SetParent(_selfParent);
transform.localPosition = Vector3.zero;
}
_canvasGroup.blocksRaycasts = true;//使射線不能穿過Item,也就是不能檢測到Item下面的物體
}
}