NGUI-简易背包系统
---恢复内容开始---
最近在找工作,有点无聊,看到一个面试题,记录一下实现方式
以下:这是完成后的样子,实现了拖拽、替换功能

开始制作,首先打开NGUI->Open->Prefab Toolbar ,拉出一个background,将它的size设为400*500;

然后再拉出一个sprite,作为背包系统的格子,将其size设为100*100,命名为cell,拉到Asset作为基础prefab。然后给格子添加碰撞器,Apply一下。为了方便,我只做了4个格子。

接下来增加物品,创建一个UI Button,素材我是网上找的LOL贴图,哈哈。NGUI里也有自带的素材可以用一下。注意Item的层级要在cell之上,然后将item弄成预设,为其增加MyDragDropItem,
using UnityEngine;
using System.Collections;
public class MyDragDropItem : UIDragDropItem {
protected override System.Void OnDragDropRelease (GameObject surface)
{
base.OnDragDropRelease (surface);
Debug.Log(surface);
if(surface.tag =="cell")
{
this.transform.parent = surface.transform;
this.transform.localPosition = Vector3.zero;
}
else if(surface.tag == "item")
{
Transform parent = surface.transform.parent;
surface.transform.parent = this.transform.parent;
surface.transform.localPosition = Vector3.zero;
this.transform.parent = parent;
this.transform.localPosition = Vector3.zero;
}
}
}
因为mac里的mono不可以打中文,所以我就没有加注释,简单翻译一下,surface就是格子。物品是放在格子里的,所以格子里只能有一个物品,所以当格子里有物品时,再将另一个物品移到这个有物品的格子时所碰到的是物品而不是格子,这时,我们可以用tag来区分格子里有没有物品,有则替换,没有就直接让物品归中到格子中间。大概就是这么简单。
至于拾取功能,简单的说一下就是用NGUITools.AddChild(cell[0],item);
当然在实际工作中,物品有它的属性,还需要增加属性表,这里就不写了。
最后的样子:

浙公网安备 33010602011771号