Files
Emberwild/Assets/GAME/Script/Editor/Database/RecipeAssetFactory.cs
T
2026-06-22 23:32:46 +02:00

77 lines
2.7 KiB
C#

using System.IO;
using UnityEditor;
using UnityEngine;
using Ashwild.Crafting;
using Ashwild.Inventory;
namespace Ashwild.EditorTools
{
/// <summary>
/// Editor-only factory that creates CraftingRecipe assets for the Ashwild Database window.
/// Kept separate from the window so recipe authoring stays a single-purpose, testable helper —
/// mirrors ItemAssetFactory for items.
/// </summary>
public static class RecipeAssetFactory
{
#region Constants
private const string RecipesFolder = "Assets/GAME/ScriptableObjects/Recipes";
#endregion
#region Recipe Asset
/// <summary>
/// Creates a fresh CraftingRecipe asset under the recipes folder with a unique name, seeding
/// its recipe name and (optionally) the result item so the new asset is immediately coherent.
/// Returns the asset for selection, or null if the folder cannot be made.
/// </summary>
public static CraftingRecipe CreateRecipe(string desiredName, ItemData resultItem)
{
if (!EnsureFolder(RecipesFolder)) return null;
string safeName = string.IsNullOrWhiteSpace(desiredName) ? "NewRecipe" : desiredName.Trim();
string assetPath = AssetDatabase.GenerateUniqueAssetPath($"{RecipesFolder}/{safeName}.asset");
CraftingRecipe recipe = ScriptableObject.CreateInstance<CraftingRecipe>();
AssetDatabase.CreateAsset(recipe, assetPath);
SerializedObject so = new SerializedObject(recipe);
so.FindProperty("recipeName").stringValue = safeName;
so.FindProperty("resultQuantity").intValue = 1;
if (resultItem != null) so.FindProperty("resultItem").objectReferenceValue = resultItem;
so.ApplyModifiedPropertiesWithoutUndo();
EditorUtility.SetDirty(recipe);
AssetDatabase.SaveAssets();
return recipe;
}
#endregion
#region Internal Helpers
/// <summary>
/// Ensures a project-relative asset folder exists, creating any missing segments. Returns
/// false (and logs) when the path cannot be created.
/// </summary>
private static bool EnsureFolder(string folder)
{
if (AssetDatabase.IsValidFolder(folder)) return true;
string parent = Path.GetDirectoryName(folder).Replace('\\', '/');
string leaf = Path.GetFileName(folder);
if (!EnsureFolder(parent))
{
Debug.LogError($"[RecipeAssetFactory] Could not create folder '{folder}'.");
return false;
}
AssetDatabase.CreateFolder(parent, leaf);
return AssetDatabase.IsValidFolder(folder);
}
#endregion
}
}