首先背包中的每个物体应该在主角捡起后会生成一个预制体,背包中包括它的名字,图像,数量以及物品介绍文本,故此先建一个类Slot用于挂载在预制体上获取相关信息
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Slot : MonoBehaviour
{
// Start is called before the first frame update
public Item slotItem;
public Image slotImage;
public Text slotText;
}
完成此步操作后,再写一个代码用于生成挂载Slot的预制体InventoryManage
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InventoryManage : MonoBehaviour
{
public static InventoryManage instance;
// Start is called before the first frame update
public Slot slotPrefab;
public GameObject grid;
public Inventory myBag;
public Text itemInfo;
void Awake()
{
if (instance != null)
{
Destroy(this);
}
instance = this;
}
// Update is called once per frame
public static void CreateNewItem(Item item)
{
Slot newItem = Instantiate(instance.slotPrefab, instance.grid.transform.position, Quaternion.identity);
newItem.gameObject.transform.SetParent(instance.grid.transform);
newItem.slotItem = item;
newItem.slotImage.sprite = item.itemImage;
newItem.slotText.text = item.itemInfo.ToString();
}
}
【单例模式】
public static InventoryManage instance;是单例设计模式,六大设计模式的一种
保证应用这个模式时,单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个全局对象,这样有利于我们协调系统整体的行为。
后面Awake()中也是一部分
【静态函数】
静态函数对象可以用类访问而不能够被实例化对象访问
比如
InventoryManage.CreateNewItem(thisItem); √
InventoryManage.instance.CreateNewItem(thisItem);×
【创建新物品函数】
在上一篇文章中通过调用这个函数来实现物品在背包中的显示