using System.Collections.Generic; using UnityEditor; using UnityEngine; using Ashwild.Inventory; namespace Ashwild.EditorTools { /// /// Editor tool that (re)builds the ItemDatabase by scanning the project for every ItemData /// asset and writing them, in a stable order, into Resources/ItemDatabase. Run it whenever /// items are added or removed so their network ids stay in sync across builds. /// public static class ItemDatabaseBuilder { #region Constants private const string ResourcesFolder = "Assets/GAME/Resources"; private const string DatabasePath = "Assets/GAME/Resources/ItemDatabase.asset"; #endregion #region Menu /// /// Finds all ItemData assets and stores them in the (auto-created) ItemDatabase. /// [MenuItem("Tools/Ashwild/Rebuild Item Database")] public static void Rebuild() { ItemDatabase database = GetOrCreateDatabase(); string[] guids = AssetDatabase.FindAssets("t:ItemData"); List items = new List(guids.Length); for (int i = 0; i < guids.Length; i++) { string path = AssetDatabase.GUIDToAssetPath(guids[i]); ItemData item = AssetDatabase.LoadAssetAtPath(path); if (item != null) items.Add(item); } // Stable order by asset name so ids don't shuffle between rebuilds. items.Sort((a, b) => string.CompareOrdinal(a.name, b.name)); database.EditorSetItems(items.ToArray()); EditorUtility.SetDirty(database); AssetDatabase.SaveAssets(); Debug.Log($"[ItemDatabaseBuilder] Registered {items.Count} items into {DatabasePath}.", database); } #endregion #region Internal Helpers /// /// Loads the ItemDatabase, creating it (and the Resources folder) if missing. /// private static ItemDatabase GetOrCreateDatabase() { ItemDatabase database = AssetDatabase.LoadAssetAtPath(DatabasePath); if (database != null) return database; if (!AssetDatabase.IsValidFolder(ResourcesFolder)) AssetDatabase.CreateFolder("Assets/GAME", "Resources"); database = ScriptableObject.CreateInstance(); AssetDatabase.CreateAsset(database, DatabasePath); AssetDatabase.SaveAssets(); return database; } #endregion } }