AddComponentToAssetCommand.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. using System;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using LLM.Editor.Helper;
  6. using JetBrains.Annotations;
  7. using Object = UnityEngine.Object;
  8. namespace LLM.Editor.Commands
  9. {
  10. [Serializable]
  11. public class AddComponentParams
  12. {
  13. public string scriptName;
  14. public string componentName;
  15. public string targetIdentifier; // This is now a LOGICAL name
  16. public string childPath; // Optional path to a child object, e.g., "Launcher/SpawnPoint"
  17. }
  18. [UsedImplicitly]
  19. public class AddComponentToAssetCommand : ICommand
  20. {
  21. private readonly AddComponentParams _params;
  22. public AddComponentToAssetCommand(string jsonParams)
  23. {
  24. _params = jsonParams?.FromJson<AddComponentParams>();
  25. }
  26. public CommandOutcome Execute(Data.CommandContext context)
  27. {
  28. if (_params == null || string.IsNullOrEmpty(_params.targetIdentifier) || (string.IsNullOrEmpty(_params.scriptName) && string.IsNullOrEmpty(_params.componentName)))
  29. {
  30. context.ErrorMessage = "Invalid parameters. Target identifier and script/component name are required.";
  31. return CommandOutcome.Error;
  32. }
  33. _params.scriptName ??= _params.componentName;
  34. var targetObject = CommandUtility.ResolveIdentifier(context, _params.targetIdentifier);
  35. if (!targetObject)
  36. {
  37. var internalError = context.ErrorMessage;
  38. context.ErrorMessage = $"Could not find target with logical name '{_params.targetIdentifier}'. The object may have been deleted or the identifier map is out of sync. \nInternal error: {internalError}";
  39. return CommandOutcome.Error;
  40. }
  41. var scriptType = GetTypeByName(_params.scriptName);
  42. if (scriptType == null)
  43. {
  44. context.ErrorMessage = $"Could not find script type '{_params.scriptName}'. It may not have compiled correctly or does not exist.";
  45. return CommandOutcome.Error;
  46. }
  47. if (targetObject is not GameObject rootGo)
  48. {
  49. context.ErrorMessage = $"Target '{targetObject.name}' is not a GameObject and components cannot be added to it.";
  50. return CommandOutcome.Error;
  51. }
  52. var objectToAddComponentTo = rootGo;
  53. if (!string.IsNullOrEmpty(_params.childPath))
  54. {
  55. var childTransform = rootGo.transform.Find(_params.childPath);
  56. if (childTransform)
  57. {
  58. objectToAddComponentTo = childTransform.gameObject;
  59. }
  60. else
  61. {
  62. context.ErrorMessage = $"Could not find child at path '{_params.childPath}' on target '{rootGo.name}'.";
  63. return CommandOutcome.Error;
  64. }
  65. }
  66. // Handle whether we're editing a prefab asset or a scene instance
  67. if (PrefabUtility.IsPartOfPrefabAsset(objectToAddComponentTo))
  68. {
  69. var prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(targetObject);
  70. var prefabContents = PrefabUtility.LoadPrefabContents(prefabPath);
  71. var targetInPrefab = FindEquivalentObjectInPrefab(objectToAddComponentTo, prefabContents);
  72. if (targetInPrefab)
  73. {
  74. targetInPrefab.AddComponent(scriptType);
  75. PrefabUtility.SaveAsPrefabAsset(prefabContents, prefabPath);
  76. PrefabUtility.UnloadPrefabContents(prefabContents);
  77. Debug.Log($"[AddComponentCommand] Added component '{_params.scriptName}' to prefab at '{prefabPath}'.");
  78. }
  79. else
  80. {
  81. PrefabUtility.UnloadPrefabContents(prefabContents);
  82. context.ErrorMessage = $"Could not find equivalent of '{objectToAddComponentTo.name}' in prefab contents.";
  83. return CommandOutcome.Error;
  84. }
  85. }
  86. else // It's a scene object
  87. {
  88. var result = Undo.AddComponent(objectToAddComponentTo, scriptType);
  89. if (!result)
  90. {
  91. context.ErrorMessage = $"Failed to add component '{_params.scriptName}' to scene object '{objectToAddComponentTo.name}', mostly since it already has one.";
  92. return CommandOutcome.Error;
  93. }
  94. Debug.Log($"[AddComponentCommand] Added component '{_params.scriptName}' to scene object '{objectToAddComponentTo.name}'.");
  95. }
  96. return CommandOutcome.Success;
  97. }
  98. private static GameObject FindEquivalentObjectInPrefab(GameObject original, GameObject prefabRoot)
  99. {
  100. if (original.name == prefabRoot.name) return prefabRoot;
  101. var originalPath = AnimationUtility.CalculateTransformPath(original.transform, original.transform.root);
  102. var foundChild = prefabRoot.transform.Find(originalPath);
  103. return foundChild ? foundChild.gameObject : null;
  104. }
  105. private static Type GetTypeByName(string typeName)
  106. {
  107. return AppDomain.CurrentDomain.GetAssemblies()
  108. .Select(assembly => assembly.GetType(typeName, false)) // Be non-throwing
  109. .FirstOrDefault(type => type != null);
  110. }
  111. }
  112. }