miepzerino
2025-04-03 4f1ed3919b0ee3f89dbcbacf49990888a7d9274a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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;
    }
}