AddComponentToAssetCommand.cs 1.6 KB

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