CreatePrefabCommand.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using UnityEngine;
  2. using UnityEditor;
  3. using JetBrains.Annotations;
  4. namespace LLM.Editor.Commands
  5. {
  6. [System.Serializable]
  7. public class CreatePrefabParams
  8. {
  9. public string sourceObjectQuery; // e.g., "Racer t:Model"
  10. public string defaultName; // e.g., "Racer.prefab"
  11. }
  12. [UsedImplicitly]
  13. public class CreatePrefabCommand : ICommand
  14. {
  15. // This key is used to pass the chosen path to subsequent commands.
  16. public const string CONTEXT_KEY_PREFAB_PATH = "lastCreatedPrefabPath";
  17. private readonly CreatePrefabParams _params;
  18. public CreatePrefabCommand(string jsonParams)
  19. {
  20. _params = JsonUtility.FromJson<CreatePrefabParams>(jsonParams);
  21. }
  22. public void Execute(Data.CommandContext context)
  23. {
  24. // Step 1: Ask the user for a save path.
  25. var path = EditorUtility.SaveFilePanel("Save New Prefab", "Assets/", _params.defaultName, "prefab");
  26. if (string.IsNullOrEmpty(path))
  27. {
  28. Debug.LogWarning("[CreatePrefabCommand] User cancelled save dialog. Aborting.");
  29. // We could clear the command queue here if we want cancellation to stop everything.
  30. return;
  31. }
  32. // We need a relative path for AssetDatabase
  33. var prefabPath = "Assets" + path[Application.dataPath.Length..];
  34. // Step 2: Find the source asset.
  35. var guids = AssetDatabase.FindAssets(_params.sourceObjectQuery);
  36. if (guids.Length == 0)
  37. {
  38. Debug.LogError($"[CreatePrefabCommand] No asset found for query: '{_params.sourceObjectQuery}'");
  39. return;
  40. }
  41. var assetPath = AssetDatabase.GUIDToAssetPath(guids[0]);
  42. var sourceAsset = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
  43. // Step 3: Create the prefab.
  44. var instance = (GameObject)PrefabUtility.InstantiatePrefab(sourceAsset);
  45. PrefabUtility.SaveAsPrefabAsset(instance, prefabPath);
  46. Object.DestroyImmediate(instance);
  47. // Step 4: Store the chosen path in the context for the next commands.
  48. context.transientData[CONTEXT_KEY_PREFAB_PATH] = prefabPath;
  49. Debug.Log($"[CreatePrefabCommand] Created prefab at '{prefabPath}' from source '{assetPath}'.");
  50. }
  51. }
  52. }