InstantiatePrefabCommand.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using JetBrains.Annotations;
  3. using LLM.Editor.Helper;
  4. using UnityEditor;
  5. using UnityEngine;
  6. namespace LLM.Editor.Commands
  7. {
  8. [Serializable]
  9. public class InstantiatePrefabParams
  10. {
  11. public string prefabIdentifier; // The logical name of the prefab asset
  12. }
  13. [UsedImplicitly]
  14. public class InstantiatePrefabCommand : ICommand
  15. {
  16. private readonly InstantiatePrefabParams _params;
  17. public InstantiatePrefabCommand(string jsonParams)
  18. {
  19. _params = jsonParams.FromJson<InstantiatePrefabParams>();
  20. }
  21. public CommandOutcome Execute(Data.CommandContext context)
  22. {
  23. if (_params == null || string.IsNullOrEmpty(_params.prefabIdentifier))
  24. {
  25. context.ErrorMessage = "Invalid parameters: prefabIdentifier is required.";
  26. return CommandOutcome.Error;
  27. }
  28. var resolvedObject = CommandUtility.ResolveIdentifier(context, _params.prefabIdentifier);
  29. if (resolvedObject is not GameObject prefab)
  30. {
  31. context.ErrorMessage = $"Could not resolve prefab with logical name '{_params.prefabIdentifier}'. It may not exist or is not a valid GameObject.";
  32. return CommandOutcome.Error;
  33. }
  34. var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
  35. if (instance == null)
  36. {
  37. context.ErrorMessage = $"Failed to instantiate prefab '{prefab.name}'. It may be empty or corrupted.";
  38. return CommandOutcome.Error;
  39. }
  40. Undo.RegisterCreatedObjectUndo(instance, "Instantiate " + instance.name);
  41. Selection.activeObject = instance;
  42. Debug.Log($"[InstantiatePrefabCommand] Instantiated '{prefab.name}' into the scene.");
  43. // Create a new logical name for the instance in the scene
  44. var logicalName = $"{instance.name}_{Guid.NewGuid():N}";
  45. var pId = new Data.PersistentIdentifier
  46. {
  47. logicalName = logicalName,
  48. instanceID = instance.GetInstanceID(),
  49. path = CommandUtility.GetGameObjectPath(instance)
  50. };
  51. context.IdentifierMap[logicalName] = pId;
  52. context.CurrentSubject = logicalName;
  53. return CommandOutcome.Success;
  54. }
  55. private static string GetGameObjectPath(GameObject obj)
  56. {
  57. var path = "/" + obj.name;
  58. while (obj.transform.parent != null)
  59. {
  60. obj = obj.transform.parent.gameObject;
  61. path = "/" + obj.name + path;
  62. }
  63. return path;
  64. }
  65. }
  66. }