我不是很喜欢在这样的地方发帖,但我不知道怎么办了,所以希望这里的高手能帮我一下。 我刚开始学习这个东西,所以我按照教程写了这个代码,是为了实现一个物品栏功能的,但是它似乎没有被读取。如果能得到一些帮助,我会很感谢。 以下是没有被读取的截图,和代码。

2/2
1/2

using UnityEngine;
using System.Collections.Generic;

public class Inventory : MonoBehaviour
{
public ItemSO testItem;
public ItemSO testItem2;
public GameObject hotbarObj;
public GameObject inventorySlotParent;

private List<Slot> inventorySlots = new List<Slot>();
private List<Slot> hotbarSlots = new List<Slot>();
private List<Slot> allSlots = new List<Slot>();

private void Awake()
{
    inventorySlots.AddRange(inventorySlotParent.GetComponentsInChildren<Slot>());
    hotbarSlots.AddRange(hotbarObj.GetComponentsInChildren<Slot>());
    allSlots.AddRange(inventorySlots);
    allSlots.AddRange(hotbarSlots);
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        AddItem(testItem, 1);
    }
    else if (Input.GetKeyDown(KeyCode.F))
    {
        AddItem(testItem2, 3);
    }
}

public void AddItem(ItemSO itemToAdd, int amount)
{
    int remaining = amount;
    foreach (Slot slot in allSlots)
    {
        if (slot.HasItem() && slot.GetItem() == itemToAdd)
        {
            int currentAmount = slot.GetAmount();
            int maxStack = itemToAdd.maxStackSize;
            if (currentAmount < maxStack)
            {
                int spaceLeft = maxStack - currentAmount;
                int amountToAdd = Mathf.Min(spaceLeft, remaining);
                slot.SetItem(itemToAdd, currentAmount + amountToAdd);
                remaining -= amountToAdd;
                if (remaining <= 0)
                {
                    return;
                }
            }
        }
    }
    foreach (Slot slot in allSlots)
    {
        if (!slot.HasItem())
        {
            int amountToPlace = Mathf.Min(itemToAdd.maxStackSize, remaining);
            slot.SetItem(itemToAdd, amountToPlace);
            remaining -= amountToPlace;
            if (remaining <= 0)
            {
                return;
            }
        }
    }
    if (remaining > 0)
    {
        Debug.Log("物品栏已满,无法添加" + remaining + "个" + itemToAdd.itemName);
    }
}

}