CreateGameObjectCommand.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using LLM.Editor.Helper;
  5. using JetBrains.Annotations;
  6. namespace LLM.Editor.Commands
  7. {
  8. [Serializable]
  9. public class CreateGameObjectParams
  10. {
  11. public string gameObjectName;
  12. public string primitiveType; // Optional: e.g., "Cube", "Sphere", "Capsule"
  13. }
  14. [UsedImplicitly]
  15. public class CreateGameObjectCommand : ICommand
  16. {
  17. private readonly CreateGameObjectParams _params;
  18. public CreateGameObjectCommand(string jsonParams)
  19. {
  20. _params = jsonParams?.FromJson<CreateGameObjectParams>();
  21. }
  22. public CommandOutcome Execute(Data.CommandContext context)
  23. {
  24. if (_params == null || string.IsNullOrEmpty(_params.gameObjectName))
  25. {
  26. Debug.LogError("[CreateGameObjectCommand] Invalid parameters. A name for the GameObject is required.");
  27. return CommandOutcome.Error;
  28. }
  29. GameObject newGameObject;
  30. if (string.IsNullOrEmpty(_params.primitiveType))
  31. {
  32. // Create an empty GameObject if no primitive type is specified
  33. newGameObject = new GameObject(_params.gameObjectName);
  34. }
  35. else
  36. {
  37. // Create a primitive GameObject if a type is specified
  38. try
  39. {
  40. var type = (PrimitiveType)Enum.Parse(typeof(PrimitiveType), _params.primitiveType, true);
  41. newGameObject = GameObject.CreatePrimitive(type);
  42. newGameObject.name = _params.gameObjectName;
  43. }
  44. catch (ArgumentException)
  45. {
  46. Debug.LogError($"[CreateGameObjectCommand] Invalid primitive type: '{_params.primitiveType}'. Valid types are Cube, Sphere, Capsule, Cylinder, Plane, Quad.");
  47. return CommandOutcome.Error;
  48. }
  49. }
  50. Undo.RegisterCreatedObjectUndo(newGameObject, $"Create {newGameObject.name}");
  51. // Set the new object as the current subject so other commands can modify it
  52. context.CurrentSubject = newGameObject;
  53. Selection.activeGameObject = newGameObject;
  54. Debug.Log($"[CreateGameObjectCommand] Successfully created new GameObject named '{newGameObject.name}'.");
  55. return CommandOutcome.Success;
  56. }
  57. }
  58. }