JoeGeC
JoeGeC

Reputation: 226

Assign a sprite to a new Image programmatically

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

Answers (1)

Thomas Finch
Thomas Finch

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.

  • Add [System.Serializable] above your InventorySlot struct so that it can be viewed in the inspector.
  • Make a list of InventorySlot in this script.
  • Assign all the Image references there in inspector.
  • Then when you equip an item, instead of creating a whole new InventorySlot, just change the sprite of the appropriate slot from your list.

Upvotes: 1

Related Questions