Hệ thống Kho đồ Đơn giản
C# Code
/* --- ItemData (ScriptableObject) --- */
// (Giữ nguyên hoặc tương tự snippet scriptableobject-for-data)
// [CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")]
// public class ItemData : ScriptableObject { ... }
/* --- InventorySlot.cs (Gắn vào từng ô UI) --- */
using UnityEngine;
using UnityEngine.UI;
public class InventorySlot : MonoBehaviour
{
public Image icon;
public Button removeButton;
private ItemData item;
public void AddItem(ItemData newItem)
{
item = newItem;
icon.sprite = item.icon;
icon.enabled = true;
removeButton.interactable = true;
}
public void ClearSlot()
{
item = null;
icon.sprite = null;
icon.enabled = false;
removeButton.interactable = false;
}
public void OnRemoveButton()
{
Inventory.instance.Remove(item);
}
}
/* --- Inventory.cs (Singleton) --- */
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public static Inventory instance;
void Awake() { if(instance != null) { Destroy(gameObject); return; } instance = this; }
public List<ItemData> items = new List<ItemData>();
public int space = 20;
public delegate void OnItemChanged();
public OnItemChanged onItemChangedCallback;
public bool Add(ItemData item)
{
if (items.Count >= space) {
Debug.Log("Not enough room.");
return false;
}
items.Add(item);
onItemChangedCallback?.Invoke();
return true;
}
public void Remove(ItemData item)
{
items.Remove(item);
onItemChangedCallback?.Invoke();
}
}
/* --- InventoryUI.cs (Quản lý toàn bộ UI) --- */
using UnityEngine;
public class InventoryUI : MonoBehaviour
{
public Transform itemsParent;
private Inventory inventory;
private InventorySlot[] slots;
void Start()
{
inventory = Inventory.instance;
inventory.onItemChangedCallback += UpdateUI;
slots = itemsParent.GetComponentsInChildren<InventorySlot>();
}
void UpdateUI()
{
for (int i = 0; i < slots.Length; i++)
{
if (i < inventory.items.Count)
{
slots[i].AddItem(inventory.items[i]);
}
else
{
slots[i].ClearSlot();
}
}
}
}Một hệ thống kho đồ cơ bản sử dụng ScriptableObject cho dữ liệu vật phẩm và quản lý các ô chứa trong UI.