В моем классе Inventory , у меня сам инвентарь определен как словарь, где ключи — это объекты элементов, а значения — количества элементов (целые числа).
У меня есть GetItem(строковый ключ)< /code> в моем классе инвентаря, который возвращает элемент, если входная строка соответствует тому, что возвращается методом getName() элемента (т. е. соответствует ли входные данные имени элемента).
По какой-то причине он успешно может найдите предмет (скажем, Apple) в инвентаре, если я вызову, скажем, GetItem("Apple"), как только я беру яблоко, но всякий раз, когда я проверяю, является ли оно нулевым, оно всегда так и есть.
Инвентарь Класс:
Код: Выделить всё
public class Inventory : MonoBehaviour
{
public Dictionary inventory = new Dictionary();
public TextMeshProUGUI inventoryText;
public static event Action InventoryUpdated;
// Update is called once per frame
void Update()
{
InventoryUpdated += UpdateInventoryDisplay;
UpdateInventoryDisplay();
}
private void UpdateInventoryDisplay()
{
inventoryText.text = "";
foreach (var item in inventory)
{
inventoryText.text += $"{item.Key.getName()}: {item.Value}\n";
}
}
///
/// Method to add an item to the player's inventory.
/// Each unique item is stored as a key.
/// If an item doesn't already exist as a key, then add it to the inventory, and add it as a key.
/// Else, just increment the count of the item.
///
public void Add(Item item){
if (inventory.ContainsKey(item)){
inventory[item] += 1;
}
else {
inventory.Add(item, 1);
}
// Trigger the InventoryUpdated event
InventoryUpdated?.Invoke();
}
///
/// Method to use an item in the inventory dictionary.
/// Need to specify what item to use, and how many.
///
public void Use(Item item, int amount){
if (inventory.ContainsKey(item)){
inventory[item] -= amount;
if (inventory[item]
Подробнее здесь: [url]https://stackoverflow.com/questions/79325273/unity3d-item-is-successfully-found-in-inventory-but-getitem-is-still-null[/url]