-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptableDatabase.cs
More file actions
120 lines (96 loc) · 2.89 KB
/
Copy pathScriptableDatabase.cs
File metadata and controls
120 lines (96 loc) · 2.89 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
namespace ArcaneOnyx.ScriptableObjectDatabase
{
/// <summary>
/// class to hold a collection of scriptable items
/// </summary>
public class ScriptableDatabase<T> : ScriptableObject where T : ScriptableItem
{
[SerializeField] protected List<T> items = new();
[SerializeField, HideInInspector] private int id = 0;
public int Count => items.Count;
public IReadOnlyList<T> Items => items;
private int GetUniqueId() => id++;
public T GetItem(string itemId) => items.Find(x => x.Id == itemId);
public T GetItemByName(string itemName)
{
return items.Find(x => x.name == itemName);
}
public void OnSave()
{
foreach (var item in items)
{
item.OnSave();
}
}
public void AddItem(T item)
{
if (items.Contains(item)) return;
string id = GetId(GetUniqueId());
item.SetId(id);
items.Add(item);
item.name = "New Item";
item.Name = item.name;
#if UNITY_EDITOR
AssetDatabase.AddObjectToAsset(item, this);
EditorUtility.SetDirty(this);
#endif
}
private string GetId(int idx)
{
#if UNITY_EDITOR
string assetPath = AssetDatabase.GetAssetPath(this);
string guid = AssetDatabase.AssetPathToGUID(assetPath);
return $"{guid}_{idx}";
#else
return string.Empty;
#endif
}
public string GetGuid()
{
#if UNITY_EDITOR
string assetPath = AssetDatabase.GetAssetPath(this);
string guid = AssetDatabase.AssetPathToGUID(assetPath);
return guid;
#else
return string.Empty;
#endif
}
public void MigrateIds()
{
foreach (var item in items)
{
if (int.TryParse(item.Id, out int idx))
{
item.SetId(GetId(idx));
}
}
#if UNITY_EDITOR
EditorUtility.SetDirty(this);
#endif
}
public void RemoveItem(T item)
{
if (!Contains(item)) return;
items.Remove(item);
#if UNITY_EDITOR
DestroyImmediate(item, true);
EditorUtility.SetDirty(this);
#endif
}
public void SwapItems(T a, T b)
{
int aIndex = items.IndexOf(a);
int bIndex = items.IndexOf(b);
items[aIndex] = b;
items[bIndex] = a;
}
public int GetItemIndex(T item) => items.IndexOf(item);
public bool Contains(T item) => items.Contains(item);
public IEnumerable<T> GetItems() => items;
}
}