Unity3D游戏开发——显示物品的仓库UI

访问仓库物品列表的方法

  • 为了在UI中显示物品列表,我们需要给InventoryManager添加两个能够访问它的公有方法;
  • 代码:
···
    public List<string> GetItemList()  //返回仓库中的物品列表
    {
        List<string> list = new List<string>(_items.Keys);  //返回所有Dictionary键的列表
        return list;
    }

    public int GetItemCount(string name)  //返回仓库中一个指定物品到的个数
    {
        if (_items.ContainsKey(name))
        {
            return _items[name];
        }
        return 0;
    }
···

创建图片目录

  • 在UI中,物品将以图标的形式显示,所以我们需要将这些照片导入项目中;
  • 创建一个Resources目录,然后在该目录下创建一个Icon目录;

显示仓库的脚本BasicUI

  • 创建一个空的名为Controller的对象,然后将BasicUI脚本付给它;
  • 代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///<summary>
///4.14 
///显示仓库
///</summary>

public class BasicUI : MonoBehaviour 
{
    void OnGUI()
    {
        int posX = 10;
        int posY = 10;
        int width = 100;
        int height = 30;
        int buffer = 10;

        List<string> itemList = Managers.Inventory.GetItemList();
        if(itemList.Count == 0 )    //当仓库为空时,打印一条控制台消息
        {
            GUI.Box(new Rect(posX, posY, width, height), "No Items");
        }

        foreach (string item in itemList)
        {
            int count = Managers.Inventory.GetItemCount(item);
            Texture2D image = Resources.Load<Texture2D>("Icons/" + item);  //从Resources目录中加载资源的方法
            GUI.Box(new Rect(posX, posY, width, height), new GUIContent("(" + count + ")", image));
            posX += width + buffer;  //循环中每次向一边偏移
        }
    }
}
  • 每个MonoBehaviour会自动响应OnGUI方法,在3D场景被渲染之后,这个方法在每一帧中都会执行;
  • Resources.Load()方法用于从Resources目录中加载资源。该方法是一个根据名称来加载资源的简便方法,注意物品的名称将作为参数。当然,我们必须要指定要加载的类型,否则,这个方法的返回类型是通用对象类型;

参考资料

  • Unity3D之OnGUI知识总结;
  • 《Unity 5实战——使用C#和Unity开发多平台游戏》,作者Joseph Hocking ,译者蔡俊鸿。
posted @ 2019-04-14 22:51  苏木木木  阅读(1015)  评论(0编辑  收藏  举报