InstantiatePrefabCommand.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using JetBrains.Annotations;
  3. using LLM.Editor.Helper;
  4. using UnityEditor;
  5. using UnityEngine;
  6. namespace LLM.Editor.Commands
  7. {
  8. [Serializable]
  9. public class InstantiatePrefabParams
  10. {
  11. public string prefabIdentifier; // The logical name of the prefab asset
  12. }
  13. [UsedImplicitly]
  14. public class InstantiatePrefabCommand : ICommand
  15. {
  16. private readonly InstantiatePrefabParams _params;
  17. public InstantiatePrefabCommand(string jsonParams)
  18. {
  19. _params = jsonParams.FromJson<InstantiatePrefabParams>();
  20. }
  21. public CommandOutcome Execute(Data.CommandContext context)
  22. {
  23. if (_params == null || string.IsNullOrEmpty(_params.prefabIdentifier))
  24. {
  25. context.ErrorMessage = "Invalid parameters: prefabIdentifier is required.";
  26. return CommandOutcome.Error;
  27. }
  28. var resolvedObject = CommandUtility.ResolveIdentifier(context, _params.prefabIdentifier);
  29. if (resolvedObject is not GameObject prefab)
  30. {
  31. context.ErrorMessage = $"Could not resolve prefab with logical name '{_params.prefabIdentifier}'. It may not exist or is not a valid GameObject.";
  32. return CommandOutcome.Error;
  33. }
  34. var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
  35. if (instance == null)
  36. {
  37. context.ErrorMessage = $"Failed to instantiate prefab '{prefab.name}'. It may be empty or corrupted.";
  38. return CommandOutcome.Error;
  39. }
  40. Undo.RegisterCreatedObjectUndo(instance, "Instantiate " + instance.name);
  41. Selection.activeObject = instance;
  42. Debug.Log($"[InstantiatePrefabCommand] Instantiated '{prefab.name}' into the scene.");
  43. // Create a new logical name for the instance in the scene
  44. var logicalName = $"{_params.prefabIdentifier}_instance_{Guid.NewGuid():N}";
  45. var hierarchyPath = GetGameObjectPath(instance);
  46. context.IdentifierMap[logicalName] = hierarchyPath;
  47. context.CurrentSubject = logicalName;
  48. return CommandOutcome.Success;
  49. }
  50. private static string GetGameObjectPath(GameObject obj)
  51. {
  52. var path = "/" + obj.name;
  53. while (obj.transform.parent != null)
  54. {
  55. obj = obj.transform.parent.gameObject;
  56. path = "/" + obj.name + path;
  57. }
  58. return path;
  59. }
  60. }
  61. }