SetHierarchyCommand.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using JetBrains.Annotations;
  2. using LLM.Editor.Core;
  3. using LLM.Editor.Helper;
  4. using UnityEditor;
  5. using UnityEngine;
  6. namespace LLM.Editor.Commands
  7. {
  8. [System.Serializable]
  9. public class SetHierarchyParams
  10. {
  11. public string childIdentifier;
  12. public string parentIdentifier; // null or empty indicates root
  13. public int siblingIndex = -1; // -1 indicates end of list
  14. }
  15. [UsedImplicitly]
  16. public class SetHierarchyCommand : ICommand
  17. {
  18. private readonly SetHierarchyParams _params;
  19. public SetHierarchyCommand(string jsonParams)
  20. {
  21. _params = jsonParams?.FromJson<SetHierarchyParams>();
  22. }
  23. public CommandOutcome Execute(Data.CommandContext context)
  24. {
  25. if (_params == null || string.IsNullOrEmpty(_params.childIdentifier))
  26. {
  27. context.ErrorMessage = "Invalid parameters: childIdentifier is required.";
  28. return CommandOutcome.Error;
  29. }
  30. var childObject = CommandUtility.ResolveIdentifier(context, _params.childIdentifier);
  31. if (childObject is not GameObject childGo)
  32. {
  33. context.ErrorMessage = $"Could not find a valid child GameObject with logical name: '{_params.childIdentifier}'";
  34. return CommandOutcome.Error;
  35. }
  36. Transform parentTransform = null;
  37. if (!string.IsNullOrEmpty(_params.parentIdentifier))
  38. {
  39. var parentObject = CommandUtility.ResolveIdentifier(context, _params.parentIdentifier);
  40. if (parentObject is not GameObject parentGo)
  41. {
  42. context.ErrorMessage = $"Could not find a valid parent GameObject with logical name: '{_params.parentIdentifier}'";
  43. return CommandOutcome.Error;
  44. }
  45. parentTransform = parentGo.transform;
  46. }
  47. Undo.SetTransformParent(childGo.transform, parentTransform, "Reparent GameObject");
  48. if (_params.siblingIndex > -1)
  49. {
  50. childGo.transform.SetSiblingIndex(_params.siblingIndex);
  51. }
  52. // Update the identifier map with the new path
  53. if (context.IdentifierMap.TryGetValue(_params.childIdentifier, out var pId))
  54. {
  55. pId.path = CommandUtility.GetGameObjectPath(childGo);
  56. SessionManager.SaveIdentifierMap(context.IdentifierMap);
  57. Debug.Log($"[SetHierarchyCommand] Set parent of '{childGo.name}' to '{(parentTransform ? parentTransform.name : "root")}'. Path updated to '{pId.path}'.");
  58. }
  59. else
  60. {
  61. Debug.LogWarning($"[SetHierarchyCommand] Could not find logical name '{_params.childIdentifier}' in map to update its path.");
  62. }
  63. return CommandOutcome.Success;
  64. }
  65. }
  66. }