108 lines
3.1 KiB
C#
108 lines
3.1 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Data.ScriptableObjects.Items;
|
|
using Types.Items;
|
|
using UnityEngine;
|
|
|
|
namespace Data.ScriptableObjects
|
|
{
|
|
[CreateAssetMenu(fileName = "ItemDatabase", menuName = "Game/Item Database")]
|
|
public class ItemDatabase : ScriptableObject
|
|
{
|
|
public static ItemDatabase Instance;
|
|
[SerializeField] private int lastAssignedId;
|
|
|
|
private readonly Dictionary<int, GameItem> _itemDictionary = new();
|
|
[SerializeField] public List<GameItem> AllItems = new();
|
|
|
|
|
|
public void Awake()
|
|
{
|
|
if (Instance == null) Instance = this;
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
_itemDictionary.Clear();
|
|
foreach (var item in AllItems) _itemDictionary[item.ID] = item;
|
|
}
|
|
|
|
public int GetNextId()
|
|
{
|
|
return ++lastAssignedId;
|
|
}
|
|
|
|
|
|
public void AddItem(GameItem item)
|
|
{
|
|
if (!_itemDictionary.ContainsKey(item.ID))
|
|
{
|
|
AllItems.Add(item);
|
|
_itemDictionary[item.ID] = item;
|
|
}
|
|
}
|
|
|
|
public GameItem GetItemById(int id)
|
|
{
|
|
if (_itemDictionary.TryGetValue(id, out var item)) return item.Clone();
|
|
return null;
|
|
}
|
|
|
|
public GameItem GetItemByName(string searchName)
|
|
{
|
|
return AllItems.Find(item => item.ItemName == searchName)?.Clone();
|
|
}
|
|
|
|
public void RemoveItem(GameItem item)
|
|
{
|
|
if (_itemDictionary.ContainsKey(item.ID))
|
|
{
|
|
AllItems.Remove(item);
|
|
_itemDictionary.Remove(item.ID);
|
|
}
|
|
}
|
|
|
|
public int GetMaxId()
|
|
{
|
|
lastAssignedId = 0;
|
|
foreach (var item in AllItems)
|
|
if (item.ID > lastAssignedId)
|
|
lastAssignedId = item.ID;
|
|
|
|
return lastAssignedId;
|
|
}
|
|
|
|
public void LoadAllItems()
|
|
{
|
|
AllItems.Clear();
|
|
var scriptableGameItems = Resources.LoadAll<GameItemSo>("GameItems");
|
|
|
|
// loop over them all, convert each to GameItem and add to AllItems
|
|
foreach (var scriptableGameItem in scriptableGameItems)
|
|
{
|
|
var gameItem = scriptableGameItem.Clone();
|
|
AllItems.Add(gameItem);
|
|
}
|
|
|
|
// AllItems.AddRange();
|
|
GetMaxId();
|
|
if (lastAssignedId == 0) lastAssignedId = GetNextId();
|
|
|
|
// check ids of all items.
|
|
// id should not be zero, reassign to lastAssignedId if it is.
|
|
foreach (var item in AllItems.Where(item => item.ID == 0))
|
|
item.ID = GetNextId();
|
|
// EditorUtility.SetDirty(item);
|
|
|
|
foreach (var item in AllItems) _itemDictionary[item.ID] = item;
|
|
}
|
|
|
|
|
|
// get random item by type
|
|
public GameItem GetRandomItemByType(ItemType type)
|
|
{
|
|
var items = AllItems.FindAll(item => item.Type == type);
|
|
return items[Random.Range(0, items.Count - 1)].Clone();
|
|
}
|
|
}
|
|
} |