AddComponentToAssetCommand.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. using System;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using LLM.Editor.Helper;
  6. using JetBrains.Annotations;
  7. namespace LLM.Editor.Commands
  8. {
  9. [Serializable]
  10. public class AddComponentParams
  11. {
  12. public string scriptName;
  13. public string componentName;
  14. public string targetIdentifier;
  15. public string childPath; // Optional path to a child object, e.g., "Launcher/SpawnPoint"
  16. }
  17. [UsedImplicitly]
  18. public class AddComponentToAssetCommand : ICommand
  19. {
  20. private readonly AddComponentParams _params;
  21. public AddComponentToAssetCommand(string jsonParams)
  22. {
  23. _params = jsonParams?.FromJson<AddComponentParams>();
  24. }
  25. public CommandOutcome Execute(Data.CommandContext context)
  26. {
  27. if (_params == null || string.IsNullOrEmpty(_params.targetIdentifier) || (string.IsNullOrEmpty(_params.scriptName) && string.IsNullOrEmpty(_params.componentName)))
  28. {
  29. Debug.LogError("[AddComponentCommand] Invalid parameters. Target identifier and script name are required.");
  30. return CommandOutcome.Error;
  31. }
  32. _params.scriptName ??= _params.componentName;
  33. var targetObject = ResolveIdentifier(_params.targetIdentifier);
  34. if (!targetObject)
  35. {
  36. Debug.LogError($"[AddComponentCommand] Could not find target with identifier '{_params.targetIdentifier}'.");
  37. return CommandOutcome.Error;
  38. }
  39. var scriptType = GetTypeByName(_params.scriptName);
  40. if (scriptType == null)
  41. {
  42. Debug.LogError($"[AddComponentCommand] Could not find script type '{_params.scriptName}'. Did it compile?");
  43. return CommandOutcome.Error;
  44. }
  45. // Determine if we are adding to the root object or a child
  46. GameObject objectToAddComponentTo = null;
  47. if (targetObject is GameObject rootGo)
  48. {
  49. if (string.IsNullOrEmpty(_params.childPath))
  50. {
  51. objectToAddComponentTo = rootGo;
  52. }
  53. else
  54. {
  55. var childTransform = rootGo.transform.Find(_params.childPath);
  56. if (childTransform)
  57. {
  58. objectToAddComponentTo = childTransform.gameObject;
  59. }
  60. else
  61. {
  62. Debug.LogError($"[AddComponentCommand] Could not find child at path '{_params.childPath}' on target '{rootGo.name}'.");
  63. return CommandOutcome.Error;
  64. }
  65. }
  66. }
  67. if (!objectToAddComponentTo)
  68. {
  69. Debug.LogError($"[AddComponentCommand] Target '{targetObject.name}' is not a GameObject or the child path is invalid.");
  70. return CommandOutcome.Error;
  71. }
  72. // Handle whether we're editing a prefab asset or a scene instance
  73. if (PrefabUtility.IsPartOfPrefabAsset(objectToAddComponentTo))
  74. {
  75. var prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(targetObject);
  76. var prefabContents = PrefabUtility.LoadPrefabContents(prefabPath);
  77. // Find the equivalent object within the loaded prefab contents
  78. var targetInPrefab = FindEquivalentObjectInPrefab(objectToAddComponentTo, prefabContents);
  79. if (targetInPrefab)
  80. {
  81. targetInPrefab.AddComponent(scriptType);
  82. PrefabUtility.SaveAsPrefabAsset(prefabContents, prefabPath);
  83. PrefabUtility.UnloadPrefabContents(prefabContents);
  84. Debug.Log($"[AddComponentCommand] Added component '{_params.scriptName}' to prefab at '{prefabPath}'.");
  85. }
  86. else
  87. {
  88. PrefabUtility.UnloadPrefabContents(prefabContents);
  89. Debug.LogError($"[AddComponentCommand] Could not find equivalent of '{objectToAddComponentTo.name}' in prefab contents.");
  90. return CommandOutcome.Error;
  91. }
  92. }
  93. else // It's a scene object
  94. {
  95. Undo.AddComponent(objectToAddComponentTo, scriptType);
  96. Debug.Log($"[AddComponentCommand] Added component '{_params.scriptName}' to scene object '{objectToAddComponentTo.name}'.");
  97. }
  98. return CommandOutcome.Success;
  99. }
  100. private static GameObject FindEquivalentObjectInPrefab(GameObject original, GameObject prefabRoot)
  101. {
  102. if (original.name == prefabRoot.name) return prefabRoot; // Simple case
  103. var originalPath = AnimationUtility.CalculateTransformPath(original.transform, original.transform.root);
  104. var foundChild = prefabRoot.transform.Find(originalPath);
  105. return foundChild ? foundChild.gameObject : null;
  106. }
  107. private static UnityEngine.Object ResolveIdentifier(string identifier)
  108. {
  109. if (string.IsNullOrEmpty(identifier)) return null;
  110. if (int.TryParse(identifier, out var instanceId))
  111. {
  112. return EditorUtility.InstanceIDToObject(instanceId);
  113. }
  114. var path = AssetDatabase.GUIDToAssetPath(identifier);
  115. return !string.IsNullOrEmpty(path) ? AssetDatabase.LoadAssetAtPath<GameObject>(path) : null;
  116. }
  117. private static Type GetTypeByName(string typeName)
  118. {
  119. return AppDomain.CurrentDomain.GetAssemblies().Select(assembly => assembly.GetType(typeName)).FirstOrDefault(type => type != null);
  120. }
  121. }
  122. }