Reputation: 226
I have a struct, InventorySlot, that holds an Image, and an Item class that holds a Sprite. When I click on a specific inventory slot I want to equip that item, but when I try to assign the Sprite to the Image on a new InventorySlot object, it's coming up with a null reference error.
public override void Click(Inventory inventory)
{
var inventorySlot = new InventorySlot();
inventorySlot.Image.sprite = Item.sprite; // TODO: This line is throwing an exception
inventorySlot.InventoryItem = this;
inventory.armourSlot.EquipItem(inventorySlot);
}
Is there a way that I can do this?
Upvotes: 0
Views: 239
Reputation: 522
When you make a new instance of InventorySlot, it doesn't automatically create the components for the variables inside it. So after initializing inventorySlot, you need to set Image to whatever Image component you want it to use. That way it's not null.
Alternatively, I recommend doing this differently in general.
Upvotes: 1