A
A
AndRussia2021-11-24 17:59:51
C++ / C#
AndRussia, 2021-11-24 17:59:51

What is the correct way to call a function in a class?

Hello. I have an AddItem method in the Inventory class

public void AddItem(int id, Item item, int count)
    {
        items[id].id = item.id;
        items[id].count = count;
        items[id].itemGameObject.GetComponent<Image>().sprite = item.img;
        if (count > 1 && item.id != 0)
        {
            items[id].itemGameObject.GetComponentInChildren<Text>().text = count.ToString();
        } else
        {
            items[id].itemGameObject.GetComponentInChildren<Text>().text = "";
        }
    }

I am in another file, in the RockTrigger class, trying to add an item to this inventory system of mine
Inventory inv = new Inventory();
inv.AddItem(0, inv.items[1], 1);

In Unity itself, I set items for the items variable
PQHDF.png
and when using inv.AddItem(0, inv.items[1], 1); I get the following error:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
As I understand it, it considers that there is no item with id 1 in items. But it's not. What am I doing wrong?

Update:
I made a mistake, I should have used inv.data.items[1]. data is taken from another file and class
public class DataBase : MonoBehaviour
{
    public List<Item> items = new List<Item>();
}

And the error is accordingly different
NullReferenceException: Object reference not set to an instance of an object
RockTrigger.Update () (at Assets/Scripts/RockTrigger.cs:26)

The same line 26:
inv.AddItem(0, inv.data.items [eleven);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2021-11-24
@freeExec

inv.AddItem(0, inv.items[1], 1);
You've just created an empty inventory, but you're trying to add (though code-replace) the null element as the first element.
Where does the first element to replace come from?
Where does the null element come from?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question