Learn how to equip items in player holders dynamically using code.
This sample demonstrates how to equip items into player holders either by targeting any available holder or specifying a specific one. It's a helpful reference for integrating runtime equipment logic into your gameplay systems.
using Inventory.Scripts.Core.Controllers;using Inventory.Scripts.Core.Items;using Inventory.Scripts.Core.ScriptableObjects.Items;using UnityEngine;namespace Inventory.Samples{ public class EquipInPlayerHolders : MonoBehaviour { [SerializeField] private ItemDataSo itemDataSo; private void Update() { // This creates the item instance. You don't need to do this in the flow if you're already // working with an ItemTable instead of the ItemDataSo ScriptableObject. var itemInstance = StaticInventoryContext.CreateItemTable(itemDataSo); if (Input.GetKeyDown(KeyCode.J)) { EquipInAnyEmptyPlayerHolder(itemInstance); } if (Input.GetKeyDown(KeyCode.L)) { EquipInSpecificPlayerHolder(itemInstance, "62c55f0f-f2d1-4f46-83bd-58675d1a9652"); } } public void EquipInAnyEmptyPlayerHolder(ItemTable itemToEquip) { var holderToEquip = StaticInventoryContext.InventorySupplierSo.FindPlayerHolderToEquipItem(itemToEquip); if (holderToEquip == null) { // Could not find a holder to equip the item. // Handle the scenario here. return; } holderToEquip.Equip(itemToEquip); } /// <summary> /// Specifies how you can equip an item directly into a specific holder. /// </summary> /// <param name="itemToEquip">The item to be equipped in the holder.</param> /// <param name="holderUid">The holder UID, which can be obtained from uiHolder.uniqueUid.Uid or holderData.id (they should match).</param> public void EquipInSpecificPlayerHolder(ItemTable itemToEquip, string holderUid) { var playerInventory = StaticInventoryContext.GetPlayerInventory(); var holderToEquip = playerInventory.Holders.Find(holder => holder.id == holderUid); if (holderToEquip == null || holderToEquip.isEquipped) { // Could not find the holder to equip, or the item is already equipped. // Handle the scenario here. return; } holderToEquip.Equip(itemToEquip); } }}
If you'd like to automatically equip the item into a compatible holder (when not equipped already), replace your existing PickEnvironmentItem method with the version below:
public ItemTable PickEnvironmentItem(Holder itemHolder){ var itemWillBeEquippedOrStored = itemHolder.GetItemEquipped(); var holderToEquipUid = FindPlayerHolderToEquipItem(itemWillBeEquippedOrStored); var holderData = holderToEquipUid?.GetHolderData(); // Equip item if a compatible holder was found if (holderToEquipUid != null && holderData != null) { holderData.Equip(itemWillBeEquippedOrStored); Destroy(itemHolder.gameObject); return itemWillBeEquippedOrStored; } // Fallback: Place item into the inventory grid var gridResponse = PlaceItemInPlayerInventory(itemWillBeEquippedOrStored); if (gridResponse != GridResponse.Inserted) return null; Destroy(itemHolder.gameObject); return itemWillBeEquippedOrStored;}