ItemCreationMenu.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 ItemCreationMenu
  13. {
  14. private const string WeaponsResourcePath = "Assets/Resources/Items/Weapons/";
  15. private const string ArmorResourcePath = "Assets/Resources/Items/Armor/";
  16. private const string ConsumableResourcePath = "Assets/Resources/Items/Consumables/";
  17. [MenuItem("Assets/Create/MazeGen/Weapon", priority = 20)]
  18. public static void CreateWeapon()
  19. {
  20. CreateItemAsset<Weapon>(WeaponsResourcePath, "NewWeapon.asset");
  21. }
  22. [MenuItem("Assets/Create/MazeGen/Armor", priority = 20)]
  23. public static void CreateArmor()
  24. {
  25. CreateItemAsset<Armor>(ArmorResourcePath, "NewArmor.asset");
  26. }
  27. [MenuItem("Assets/Create/MazeGen/Consumable", priority = 20)]
  28. public static void CreateConsumable()
  29. {
  30. CreateItemAsset<Consumable>(ConsumableResourcePath, "NewConsumable.asset");
  31. }
  32. /// <summary>
  33. /// Generic method to create and save an item asset.
  34. /// Creates the resource folder if it doesn't exist, then shows a save dialog.
  35. /// </summary>
  36. private static void CreateItemAsset<T>(string defaultPath, string defaultName) where T : Item
  37. {
  38. // Ensure the directory exists
  39. if (!Directory.Exists(defaultPath))
  40. {
  41. Directory.CreateDirectory(defaultPath);
  42. AssetDatabase.Refresh();
  43. }
  44. // Show save dialog
  45. string savePath = EditorUtility.SaveFilePanelInProject(
  46. $"Create New {typeof(T).Name}",
  47. defaultName,
  48. "asset",
  49. "Choose a location and name for the new asset",
  50. defaultPath
  51. );
  52. if (string.IsNullOrEmpty(savePath))
  53. return; // User cancelled
  54. // Create the asset
  55. T newItem = ScriptableObject.CreateInstance<T>();
  56. newItem.name = Path.GetFileNameWithoutExtension(savePath);
  57. // Save it
  58. AssetDatabase.CreateAsset(newItem, savePath);
  59. AssetDatabase.SaveAssets();
  60. AssetDatabase.Refresh();
  61. // Select it in the Project window
  62. EditorGUIUtility.PingObject(newItem);
  63. Debug.Log($"Created {typeof(T).Name}: {savePath}");
  64. }
  65. }
  66. }
  67. #endif