0

I have a method ListItems() witch i want to be updated whenever I open the Inventory for my game in Unity. Whenever I try this I get the error: member InventoryManager.ListItems() cannot be accessed with an instance reference; qualify it with a type name instead

None of these methods are static, so I'm a bit confused here...

ListItems() :

public void ListItems()
{
    foreach(var item in Items)
    {
        GameObject obj = Instantiate(InventoryItem, ItemContent);
        var itemName = obj.transform.Find("Item/ItemName").GetComponent<Text>();
        var itemIcon = obj.transform.Find("Item/ItemIcon").GetComponent<Image>();

        itemName.text = item.itemName;
        itemIcon.sprite = item.icon;
    }
}

Update() from a different class:

public GameObject inventory;
public InventoryManager i;

  public void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        InventoryManager.GetComponent<InventoryManager>().ListItems();
        inventory.gameObject.SetActive(!inventory.gameObject.activeSelf);
       
    }
}
shingo
  • 18,436
  • 5
  • 23
  • 42
Potato
  • 21
  • 2

1 Answers1

0

Your InventoryManager is a reference to your script so you don't actually need to call the GetComponent<InventoryManager>().

You just simply call it like this:

i.ListItems();

Or, if you want to use the GetComponent<InventoryManager>() you use it on the gameObject that your script is attached to, for example if public GameObject inventory; has attached to it the InventoryManager script then you can use the following code:

inventory.GetComponent<InventoryManager>().ListItems();

Using the GetComponent method is performance heavy, and it's not required to call it everytime, you can call it only once at the Awake() or Start() method to get the reference that you want and then just simply use the cached reference.

Pavlos Mavris
  • 331
  • 1
  • 2
  • 12
  • Thanks for your answer!:) Would this not be possible to do if InventoryManager was a sigleton class?Earlier I tried some different things, and I was able to solve it calling "InventoryManager.i.ListItems()" in the Inventory class, where "i" is derived from the InventoryManager class. – Potato Nov 05 '22 at 11:47