using UnityEngine; using UnityEditor; using JetBrains.Annotations; namespace LLM.Editor.Commands { [System.Serializable] public class AddComponentToAssetParams { public string scriptName; } [UsedImplicitly] public class AddComponentToAssetCommand : ICommand { private readonly AddComponentToAssetParams _params; public AddComponentToAssetCommand(string jsonParams) { _params = JsonUtility.FromJson(jsonParams); } public void Execute(Data.CommandContext context) { // Use the context key defined in CreatePrefabCommand if (!context.transientData.TryGetValue(CreatePrefabCommand.CONTEXT_KEY_PREFAB_PATH, out var pathObj)) { Debug.LogError("[AddComponentToAssetCommand] Could not find prefab path in context."); return; } var prefabPath = pathObj as string; var prefabContents = PrefabUtility.LoadPrefabContents(prefabPath); var scriptType = System.Type.GetType($"{_params.scriptName}, Assembly-CSharp"); if (scriptType == null) { Debug.LogError($"[AddComponentToAssetCommand] Could not find script type '{_params.scriptName}'. Did it compile?"); PrefabUtility.UnloadPrefabContents(prefabContents); return; } prefabContents.AddComponent(scriptType); PrefabUtility.SaveAsPrefabAsset(prefabContents, prefabPath); PrefabUtility.UnloadPrefabContents(prefabContents); Debug.Log($"[AddComponentToAssetCommand] Added component '{_params.scriptName}' to prefab at '{prefabPath}'."); } } }