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