SetHierarchyCommand.cs 2.3 KB

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