Get 25% off your next order from the Unity Asset Store: YW86GYBU8S.
Forum begins after the advertisement:
[Part 20] Null Reference Error in UIInventoryIconDisplay
Home › Forums › Video Game Tutorial Series › Creating a Rogue-like Shoot-em Up in Unity › [Part 20] Null Reference Error in UIInventoryIconDisplay
- This topic has 3 replies, 2 voices, and was last updated 1 year, 4 months ago by
Terence.
-
AuthorPosts
-
June 21, 2024 at 1:08 am #15123::
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.<code>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; } } }</code>June 21, 2024 at 3:23 pm #15125::Jason, the Items inside
weaponSlotsandpassiveSlotsare automatically assigned by the script when you get a new item. If the variables are not assigned, you will need to check if yourPlayerInventory.Add()function is written correctly.Alternatively, the null reference could also be coming from
item.datainstead ofitem. You may want to add the following lines into your code to ascertain that the issue is withitemand notitem.databy seeing which of the variables printed is null.if (icon) { print(item); print(item.data); print("---------"); icon.sprite = item.data.icon; }June 22, 2024 at 12:43 am #15130::I found a fix. I solved it after swapping scripts inside if statement. I moved scripts inside if(item) to else and else to if(item).
<code>if (iconObj) { Image icon = iconObj.GetComponent<Image>(); if (item) { icon.color = new Color(1, 1, 1, 1); if (icon) { icon.sprite = item.data.icon; } } else { icon.color = new Color(1, 1, 1, 0); } }</code>June 22, 2024 at 12:42 pm #15131::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,
itemis used in else, whereitemis empty, soitem.data.iconwill 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; } } -
AuthorPosts
- You must be logged in to reply to this topic.
Advertisement below:
Get 25% off your next order from the Unity Asset Store: YW86GYBU8S.