AddComponentToAssetCommand.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using UnityEngine;
  2. using UnityEditor;
  3. using JetBrains.Annotations;
  4. namespace LLM.Editor.Commands
  5. {
  6. [System.Serializable]
  7. public class AddComponentToAssetParams
  8. {
  9. public string scriptName;
  10. }
  11. [UsedImplicitly]
  12. public class AddComponentToAssetCommand : ICommand
  13. {
  14. private readonly AddComponentToAssetParams _params;
  15. public AddComponentToAssetCommand(string jsonParams)
  16. {
  17. _params = JsonUtility.FromJson<AddComponentToAssetParams>(jsonParams);
  18. }
  19. public void Execute(Data.CommandContext context)
  20. {
  21. // Use the context key defined in CreatePrefabCommand
  22. if (!context.transientData.TryGetValue(CreatePrefabCommand.CONTEXT_KEY_PREFAB_PATH, out var pathObj))
  23. {
  24. Debug.LogError("[AddComponentToAssetCommand] Could not find prefab path in context.");
  25. return;
  26. }
  27. var prefabPath = pathObj as string;
  28. var prefabContents = PrefabUtility.LoadPrefabContents(prefabPath);
  29. var scriptType = System.Type.GetType($"{_params.scriptName}, Assembly-CSharp");
  30. if (scriptType == null)
  31. {
  32. Debug.LogError($"[AddComponentToAssetCommand] Could not find script type '{_params.scriptName}'. Did it compile?");
  33. PrefabUtility.UnloadPrefabContents(prefabContents);
  34. return;
  35. }
  36. prefabContents.AddComponent(scriptType);
  37. PrefabUtility.SaveAsPrefabAsset(prefabContents, prefabPath);
  38. PrefabUtility.UnloadPrefabContents(prefabContents);
  39. Debug.Log($"[AddComponentToAssetCommand] Added component '{_params.scriptName}' to prefab at '{prefabPath}'.");
  40. }
  41. }
  42. }