1.要实现在菜单格子里拖拽物品如图。
2.有物品的格子之间能够相互切换。
实现方法也有多种,第一种是通过射线检测,检测拿到格子的位置赋值,但是这个效率不是很高。
第二种是通过重写IDropHandler接口实现自带的方法OnDrop(PointerEventData evetData)这个方法在物品落下时调用。
代码:
Public Class Slot: MonoBehaviour{
public int slotID;//槽位ID
Inventory inv;//数据管理类
public void OnDrop(PointerEventData eventData){
var droppenItem = eventData.pointerDrag.GetComponent
//创建一个拖拽物体抽象类
if (inv.items [slotID].ID == -1) {
inv.items [droppenItem.slotIndex] = new Item ();
droppenItem.slotIndex = slotID;
inv.items [slotID] = droppenItem.item;
//进行赋值操作
} else if (droppenItem.slotIndex != slotID) {
Transform item = this.transform.GetChild (0);
item.GetComponent
item.transform.SetParent (inv.slots[droppenItem.slotIndex].transform);
item.transform.position = item.transform.parent.position;
inv.items [droppenItem.slotIndex] = item.GetComponent
droppenItem.slotIndex = slotID;
inv.items [slotID] = droppenItem.item;
}
}
}
然后把这个类添加到所有的拖拽物体上。如下方法
public class Inventory : MonoBehaviour {
public GameObject slot;
public GameObject item;
public List
public List
void Start () {
for(int i=0;i<20;i++){
slots.Add(Instantiate (slot));
slots[i].transform.SetParent (slotPanel.transform);
slots [i].GetComponent
items.Add (new Item ());
}
}
物品的拖拽重写
public class ItemData : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public Item item;
public int slotIndex;
public int amount = 1;
Inventory inv;
public void OnBeginDrag(PointerEventData eventData)
{
if (item != null)
{
this.transform.SetParent(transform.parent.parent);
this.transform.position = eventData.position;
}
}
public void OnDrag(PointerEventData eventData)
{
if (item != null)
{
this.transform.position = eventData.position;
}
}
public void OnEndDrag(PointerEventData eventData)
{
transform.SetParent(inv.slots[slotIndex].transform);
transform.position = transform.parent.position;
}
void Start()
{
inv = GameObject.Find("ItemDatabase").GetComponent
}
代码不全,但是实现方法差不多都有了,想要工程文件的下载地址为:https://download.csdn.net/download/martins1994/10559329