转载自:http://www.unitymanual.com/blog-10192-2705.html
在RPG游戏中,我们猪脚不断的打钱爆装备,那么这些物品需要存储在哪里?
这个是地下城与勇士的背包界面,主要是我刚好找到了这张图,就暂时用这张。
我会在最后上传我的资源,你们可以下载下来跟着我一起来制作!
ok,首先创建inventory背景图,也就是Image,调到合适大小
然后保存为prefab,再来制作slot,这里我们先创建image,再吧image和canvas renderer组件删了,只留下rect transform
然后创建子物体Image,命名为ItemIcon,Image先选择,再创建子物体button,也是选择这张图
,在button里面吧sprite swap的高亮sprite换成
命名为Overlay,主要是鼠标移动显示高亮,再创建text,
,命名为count,主要保存数目。
OK,我们也保存为prefab。
接下来我们来编写Inventory,c#代码:
首先定义变量:
接下来我们编写初始化Inventory,也就是在其中加入slot,我们写进一个方法CreatInentory(),在start中调用。
调整数值,运行就可以看到
这里注意一下:有的小伙伴永远也对不齐,因为image的锚点和轴没设置对,这里我自己是都定义在左上角。
Ok,界面部分大部分完成了,接下我们来写Item类。
Ok,为了测试更加直观我搭建了一个场景:
Inventory会增加一瓶蓝药,当移动到红色,会增加一瓶红药。
Ok,接下来我们编写Slot类,主要存放和处理Item。因为每一个slot都有一个或多个Item,也可以是没有。
[code]csharpcode:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class Slot : MonoBehaviour {
private Stack<Item> items;//这里我们用stack来存放进出Item
public Text count;//数量
public Sprite icon;//图标
public bool isEmpty//是否为空
{
get{return items.Count == 0;}
}
// Use this for initialization
void Start () {
items = new Stack<Item>();
}
// Update is called once per frame
void Update () {
}
public void AddItem(Item item)
{
items.Push(item);//吧tiem压入栈中
if (items.Count > 1)
{
count.text = items.Count.ToString();//如果数量大于1就显示
}
ChangeIcon(item.icon);
}
private void ChangeIcon(Sprite iconSprite)
{
icon = iconSprite;
}
}
然后我么回到Invetory代码,我们重新写个AddItem()方法,因为在这里可以遍历所有slots,好操作。
[code]csharpcode:
private int emptySlot;//空slot的数量
在start()初始化
[code]csharpcode:
emptySlot = rows * column;
[code]csharpcode:
public bool AddItem(Item item)
{
if (item.maxSize == 1)//先假设maxSize = 1
{
PlaceEmptySlot(item);
return true;
}
return false;
}
private bool PlaceEmptySlot(Item item)
{
if(emptySlot > 0)
{
foreach(GameObject slot in allSlots)
{
Slot slotTemp = slot.GetComponent<Slot>();
if (slotTemp.isEmpty)
{
slotTemp.AddItem(item);
emptySlot--;
return true;
}
}
}
return false;
}
OK,我们接下来把我们的猪脚给移动起来,写个Player类,然后给Mana,Health的Perfab改新加的tag “Item”,注意maxSize 必须要为1,还有要设成trigger,Player要添加rigidbody
运行试试,发现移动到篮球和红球,在inventory有Item了。
OK,今天就先到这里!好累!!!