【关于背包的制作】InventoryManage 和 静态函数相关理解

首先背包中的每个物体应该在主角捡起后会生成一个预制体,背包中包括它的名字,图像,数量以及物品介绍文本,故此先建一个类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);×

【创建新物品函数】

在上一篇文章中通过调用这个函数来实现物品在背包中的显示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值