MonsterCreationMenu.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. using UnityEditor;
  4. using System.IO;
  5. using MazeGen;
  6. namespace MazeGen.Editor
  7. {
  8. /// <summary>
  9. /// Provides context menu items for creating Weapon and Armor assets in the Unity Editor.
  10. /// Assets are created in Resources folders for easy runtime loading via Resources.Load/LoadAll.
  11. /// </summary>
  12. public class MonsterCreationMenu
  13. {
  14. private const string MonsterResourcePath = "Assets/Resources/Characters/Monsters/";
  15. [MenuItem("Assets/Create/MazeGen/Characters/Monster", priority = 20)]
  16. public static void CreateMonster()
  17. {
  18. CreateMonsterAsset<Monster>(MonsterResourcePath, "NewMonster.asset");
  19. }
  20. /// <summary>
  21. /// Generic method to create and save an item asset.
  22. /// Creates the resource folder if it doesn't exist, then shows a save dialog.
  23. /// </summary>
  24. private static void CreateMonsterAsset<T>(string defaultPath, string defaultName) where T : Monster
  25. {
  26. // Ensure the directory exists
  27. if (!Directory.Exists(defaultPath))
  28. {
  29. Directory.CreateDirectory(defaultPath);
  30. AssetDatabase.Refresh();
  31. }
  32. // Show save dialog
  33. string savePath = EditorUtility.SaveFilePanelInProject(
  34. $"Create New {typeof(T).Name}",
  35. defaultName,
  36. "asset",
  37. "Choose a location and name for the new asset",
  38. defaultPath
  39. );
  40. if (string.IsNullOrEmpty(savePath))
  41. return; // User cancelled
  42. // Create the asset
  43. T newItem = ScriptableObject.CreateInstance<T>();
  44. newItem.name = Path.GetFileNameWithoutExtension(savePath);
  45. // Save it
  46. AssetDatabase.CreateAsset(newItem, savePath);
  47. AssetDatabase.SaveAssets();
  48. AssetDatabase.Refresh();
  49. // Select it in the Project window
  50. EditorGUIUtility.PingObject(newItem);
  51. Debug.Log($"Created {typeof(T).Name}: {savePath}");
  52. }
  53. }
  54. }
  55. #endif