using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; public class Inventory : MonoBehaviour { [Header("10 Inventory Slots")] public Item[] slots = new Item[10]; public int currentSlot = 0; [SerializeField] private Transform handSlot; private GameObject currentSpawnedItem; void Awake() { Debug.Log("Inventory initialized on: " + gameObject.name); var existing = FindObjectsOfType(); if (existing.Length > 1) { Debug.LogWarning("Multiple Inventory instances found, destroying duplicate."); Destroy(gameObject); return; } DontDestroyOnLoad(gameObject); } void Update() { // handle selecting slots with number keys using new unity input system for (int i = 0; i < 10; i++) { if (Input.GetKeyDown( "" + i ) ) { // convert to int currentSlot = int.Parse("" + i); // map 1 to 0, 2 to 1, etc till 9 then 0 to 9 currentSlot = (currentSlot - 1 + slots.Length) % slots.Length; EquipSlot(currentSlot); // Debug.Log("Selected slot: " + currentSlot); var ui = FindObjectOfType(); if (ui != null) { ui.RefreshUI(); } } } float scroll = Input.GetAxis("Mouse ScrollWheel"); if (scroll > 0f) { SelectPreviousSlot(); } else if (scroll < 0f) { SelectNextSlot(); } } public void AddItem(Item newItem) { for (int i = 0; i < slots.Length; i++) { if (slots[i] == null) { slots[i] = newItem; break; } } } public bool HasItem(string itemName) { foreach (var item in slots) { if (item != null && item.itemName == itemName) { return true; } } return false; } private void SelectNextSlot() { currentSlot = (currentSlot + 1) % slots.Length; EquipSlot(currentSlot); var ui = FindObjectOfType(); if (ui != null) { ui.RefreshUI(); } } private void SelectPreviousSlot() { currentSlot = (currentSlot - 1 + slots.Length) % slots.Length; EquipSlot(currentSlot); var ui = FindObjectOfType(); if (ui != null) { ui.RefreshUI(); } } public void EquipSlot(int slotIndex) { if (currentSpawnedItem != null) { Destroy(currentSpawnedItem); } Item itemInSlot = slots[slotIndex]; GameObject prefab = itemInSlot != null ? itemInSlot.GetPrefab() : null; if (prefab != null && handSlot != null) { currentSpawnedItem = Instantiate(prefab, handSlot.position, handSlot.rotation, handSlot); currentSpawnedItem.transform.localPosition = Vector3.zero; currentSpawnedItem.transform.localRotation = Quaternion.identity; } else { currentSpawnedItem = null; } } }