using UnityEngine; using UnityEditor; using LLM.Editor.Helper; 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 = jsonParams?.FromJson(); } public CommandOutcome Execute(Data.CommandContext context) { if (context.CurrentSubject is not string prefabPath) { Debug.LogError("[AddComponentToAssetCommand] The current subject is not a valid prefab path."); return CommandOutcome.Error; } 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 CommandOutcome.Error; } prefabContents.AddComponent(scriptType); PrefabUtility.SaveAsPrefabAsset(prefabContents, prefabPath); PrefabUtility.UnloadPrefabContents(prefabContents); Debug.Log($"[AddComponentToAssetCommand] Added component '{_params.scriptName}' to prefab at '{prefabPath}'."); return CommandOutcome.Success; } } }