I’m getting a null reference error on icon.sprite = item.data.icon; I think it is happening because item is null. When I debugged it, it showed that item was null. I think that item is null because I didn’t put anything inside weaponSlots and passiveSlots in playerInventory script. I left them empty because I didn’t know what to put in there. I would appreciate it if anyone could help me find out why the error is happening.
Item item = items[i].item;
Transform iconObj = slots[i].transform.Find(iconPath);
if (iconObj)
{
Image icon = iconObj.GetComponent<Image>();
if (item)
{
icon.color = new Color(1, 1, 1, 0);
}
else
{
icon.color = new Color(1, 1, 1, 1);
if (icon)
{
icon.sprite = item.data.icon;
}
}
}
Jason, the Items inside weaponSlots and passiveSlots are automatically assigned by the script when you get a new item. If the variables are not assigned, you will need to check if your PlayerInventory.Add() function is written correctly.
Alternatively, the null reference could also be coming from item.data instead of item. You may want to add the following lines into your code to ascertain that the issue is with item and not item.data by seeing which of the variables printed is null.
if (icon)
{
print(item);
print(item.data);
print("---------");
icon.sprite = item.data.icon;
}
That’s a great spot. I didn’t notice it until you fixed it.
For anyone else reading this and wondering what the issue was, item is used in else, where item is empty, so item.data.icon will always return empty no matter what you do.
if (item)
{
icon.color = new Color(1, 1, 1, 0);
}
else
{
icon.color = new Color(1, 1, 1, 1);
if (icon)
{
icon.sprite = item.data.icon;
}
}