int x = 0;
int y = 0;
float itemSlotCellSize = 150f;
foreach (Item item in inventory.GetItemList())
{
RectTransform itemRectTransform = Instantiate(itemSlottemplate, itemSlotContainer).GetComponent<RectTransform>();
itemRectTransform.gameObject.SetActive(true);
itemRectTransform.anchoredPosition = new Vector2(x * itemSlotCellSize, y * itemSlotCellSize);
Image amage = image.GetComponent<Image>();
amage.sprite = item.GetSprite();
x++;
if(x > 4)
{
x = 0;
y++;
}
}
it say in line “amage.sprite = item.GetSprite();” this:
“NullReferenceException: Object reference not set to an instance of an object
UI_inventory.RefreshInventoryItems () (at Assets/Scripts/Inventory_System/UI_inventory.cs:35)”
anyone know why this happen and how i can fix it. thank you
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:
drag it in using the inspector
code inside this script initializes it
some OTHER external code initializes it
? something else?
This is the kind of mindset and thinking process you need to bring to this problem:
Step by step, break it down, find the problem.
Here is a clean analogy of the actual underlying problem of a null reference exception: