using System.Collections.Generic;
|
using UnityEngine;
|
|
public class ItemDatabase : MonoBehaviour
|
{
|
public static ItemDatabase Instance { get; private set; }
|
|
private List<Item> items = new List<Item>();
|
private Dictionary<string, Item> itemDictionary = new Dictionary<string, Item>();
|
private Dictionary<int, Item> itemIdDictionary = new Dictionary<int, Item>();
|
|
private void Awake()
|
{
|
if (Instance == null)
|
{
|
Instance = this;
|
LoadItemsFromResources();
|
InitializeItemDictionary();
|
}
|
else
|
{
|
Destroy(gameObject);
|
}
|
}
|
|
private void LoadItemsFromResources()
|
{
|
// Load all Item prefabs from the "Resources/Items" folder
|
GameObject[] itemPrefabs = Resources.LoadAll<GameObject>("Items");
|
|
foreach (GameObject prefab in itemPrefabs)
|
{
|
Item item = prefab.GetComponent<Item>();
|
if (item != null)
|
{
|
items.Add(item);
|
}
|
else
|
{
|
Debug.LogWarning($"Prefab {prefab.name} does not have an Item component");
|
}
|
}
|
|
if (items.Count == 0)
|
{
|
Debug.LogWarning("No items found in Resources/Items folder");
|
}
|
}
|
|
private void InitializeItemDictionary()
|
{
|
itemDictionary.Clear();
|
itemIdDictionary.Clear();
|
|
foreach (Item item in items)
|
{
|
if (!itemDictionary.ContainsKey(item.itemName))
|
{
|
itemDictionary.Add(item.itemName, item);
|
}
|
else
|
{
|
Debug.LogError($"Duplicate item name found in ItemDatabase: {item.itemName}");
|
}
|
|
if (!itemIdDictionary.ContainsKey(item.itemId))
|
{
|
itemIdDictionary.Add(item.itemId, item);
|
}
|
else
|
{
|
Debug.LogError($"Duplicate item ID found in ItemDatabase: {item.itemId}");
|
}
|
}
|
}
|
|
public Item GetItem(string itemName)
|
{
|
if (itemDictionary.TryGetValue(itemName, out Item item))
|
{
|
return item;
|
}
|
|
Debug.LogWarning($"Item not found in database: {itemName}");
|
return null;
|
}
|
|
public Item GetItem(int itemId)
|
{
|
if (itemIdDictionary.TryGetValue(itemId, out Item item))
|
{
|
return item;
|
}
|
|
Debug.LogWarning($"Item not found in database: ID {itemId}");
|
return null;
|
}
|
}
|