CreateGameObjectCommand.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using LLM.Editor.Core;
  5. using LLM.Editor.Helper;
  6. using JetBrains.Annotations;
  7. namespace LLM.Editor.Commands
  8. {
  9. [Serializable]
  10. public class CreateGameObjectParams
  11. {
  12. public string gameObjectName;
  13. public string logicalName; // A unique name for the LLM to reference this object later
  14. public string primitiveType; // Optional: e.g., "Cube", "Sphere", "Capsule"
  15. }
  16. [UsedImplicitly]
  17. public class CreateGameObjectCommand : ICommand
  18. {
  19. private readonly CreateGameObjectParams _params;
  20. public CreateGameObjectCommand(string jsonParams)
  21. {
  22. _params = jsonParams?.FromJson<CreateGameObjectParams>();
  23. }
  24. public CommandOutcome Execute(Data.CommandContext context)
  25. {
  26. if (_params == null || string.IsNullOrEmpty(_params.gameObjectName))
  27. {
  28. context.ErrorMessage = "Invalid parameters. A name for the GameObject is required.";
  29. return CommandOutcome.Error;
  30. }
  31. GameObject newGameObject;
  32. if (string.IsNullOrEmpty(_params.primitiveType))
  33. {
  34. newGameObject = new GameObject(_params.gameObjectName);
  35. }
  36. else
  37. {
  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. context.ErrorMessage = $"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. // --- Identifier Persistence Logic ---
  52. var logicalName = !string.IsNullOrEmpty(_params.logicalName) ? _params.logicalName : $"{_params.gameObjectName}_{Guid.NewGuid():N}";
  53. var pId = new Data.PersistentIdentifier
  54. {
  55. logicalName = logicalName,
  56. instanceID = newGameObject.GetInstanceID(),
  57. path = CommandUtility.GetGameObjectPath(newGameObject)
  58. };
  59. context.IdentifierMap[logicalName] = pId;
  60. SessionManager.SaveIdentifierMap(context.IdentifierMap);
  61. // Set the logical name as the current subject so the LLM knows what to reference.
  62. context.CurrentSubject = logicalName;
  63. // --- End of Logic ---
  64. Selection.activeGameObject = newGameObject;
  65. Debug.Log($"[CreateGameObjectCommand] Successfully created '{newGameObject.name}' and mapped it to logical name '{logicalName}'.");
  66. return CommandOutcome.Success;
  67. }
  68. }
  69. }