Unity GetComponentInChild

问题描述 投票:0回答:1

我正在尝试创建一个库存系统。我有一个 Item 类,我想更改根据此类中的数据创建的插槽的视觉外观,但它不起作用。我哪里出错了?

这是我的 Inventory 类,我在其中创建一个列表并尝试将 Item 中的值放入清单中的相应槽中。顺便说一句,库存槽位是预制件。

public class Inventory : MonoBehaviour
{
    public List<Item> InventoryList = new List<Item>();
    [Header("InventoryUI")]
    public GameObject InventorySlotPrefab;

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        { 
            DisplayItemsOnSlots();
        }
      
    }

    public void AddItem(int _itemId,string _itemName, int _itemAmount, Sprite _sprite)
    { 
        Item newItem = Item.CreateInstance<Item>();
        newItem.SetItemDetails(_itemId,_itemName,_itemAmount, _sprite);
        InventoryList.Add(newItem);
    }
    

    public void DisplayItemsOnSlots()
    {
        for (int i = 0; i < InventoryList.Count; i++)
        {
            Image itemImage = InventorySlotPrefab.GetComponentInChildren<Image>();
            itemImage.sprite = InventoryList[i].sprite;
        }
    
    }
}

这是我的项目类,它扩展了 ScriptableObject。

[CreateAssetMenu(fileName = "Item", menuName ="ItemSystem/BasicItem")]
public class Item : ScriptableObject
{
    public int id;
    public string name;
    public int amount;
    public Sprite sprite;

    public void SetItemDetails(int _id, string _name, int _amount, Sprite _sprite)
    {
        this.id = _id;
        this.name = _name;
        this.amount = _amount;
        this.sprite = _sprite;
    }
}
c# unity-game-engine game-development get-childitem
1个回答
0
投票

如果我理解正确的话,您将预制表单项目分配给 InventorySlotPrefab 变量。如果这是真的,那么您正在更改预制件的精灵,而不是特定实例的精灵。您必须将场景中的游戏对象(可能是库存下的物品槽)附加到 InventorySlotPrefab。

© www.soinside.com 2019 - 2024. All rights reserved.