UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"create an inventory system that is easy to customize from the Unity UI"
using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; [System.Serializable] public class Item { public string itemName; public Sprite icon; public int quantity; } public class InventorySystem : MonoBehaviour { public List<Item> items; public GameObject inventoryPanel; public GameObject inventorySlotPrefab; public Transform inventorySlotsParent; private void Start() { UpdateInventoryUI(); } public void AddItem(Item newItem) { items.Add(newItem); UpdateInventoryUI(); } public void RemoveItem(Item itemToRemove) { items.Remove(itemToRemove); UpdateInventoryUI(); } private void UpdateInventoryUI() { // Clear previous inventory slots foreach (Transform child in inventorySlotsParent) { Destroy(child.gameObject); } // Create new inventory slots for each item foreach (Item item in items) { GameObject newSlot = Instantiate(inventorySlotPrefab, inventorySlotsParent); newSlot.GetComponentInChildren<Text>().text = item.itemName + " x" + item.quantity; newSlot.GetComponentInChildren<Image>().sprite = item.icon; } } public void ToggleInventory() { inventoryPanel.SetActive(!inventoryPanel.activeSelf); } }