CommandUtility.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using LLM.Editor.Core;
  2. using UnityEditor;
  3. using UnityEngine;
  4. namespace LLM.Editor.Commands
  5. {
  6. public static class CommandUtility
  7. {
  8. public static Object ResolveIdentifier(Data.CommandContext context, string logicalName)
  9. {
  10. if (string.IsNullOrEmpty(logicalName))
  11. {
  12. context.ErrorMessage = "Identifier is null or empty.";
  13. return null;
  14. }
  15. if (!context.IdentifierMap.TryGetValue(logicalName, out var pId))
  16. {
  17. var foundObject = GameObject.Find(logicalName);
  18. if (foundObject) return foundObject;
  19. if (AssetDatabase.GUIDToAssetPath(logicalName) != "")
  20. {
  21. return AssetDatabase.LoadAssetAtPath<Object>(AssetDatabase.GUIDToAssetPath(logicalName));
  22. }
  23. context.ErrorMessage = $"Logical name '{logicalName}' not found in the identifier map.";
  24. return null;
  25. }
  26. // 1. Try to resolve by InstanceID (fastest)
  27. if (pId.instanceID != 0)
  28. {
  29. var obj = EditorUtility.InstanceIDToObject(pId.instanceID);
  30. if (obj) return obj;
  31. }
  32. // 2. Fallback to resolving by path
  33. if (!string.IsNullOrEmpty(pId.path))
  34. {
  35. var go = GameObject.Find(pId.path);
  36. if (go)
  37. {
  38. // Heal the map for the next lookup
  39. pId.instanceID = go.GetInstanceID();
  40. SessionManager.SaveIdentifierMap(context.IdentifierMap);
  41. return go;
  42. }
  43. }
  44. // 3. Fallback to resolving by GUID for assets
  45. if (!string.IsNullOrEmpty(pId.guid))
  46. {
  47. var assetPath = AssetDatabase.GUIDToAssetPath(pId.guid);
  48. if (!string.IsNullOrEmpty(assetPath))
  49. {
  50. return AssetDatabase.LoadAssetAtPath<Object>(assetPath);
  51. }
  52. }
  53. context.ErrorMessage = $"Failed to resolve identifier '{logicalName}'. The object may have been deleted or the scene/project state has changed significantly.";
  54. return null;
  55. }
  56. public static string GetGameObjectPath(GameObject obj)
  57. {
  58. if (obj == null) return null;
  59. var path = "/" + obj.name;
  60. while (obj.transform.parent)
  61. {
  62. obj = obj.transform.parent.gameObject;
  63. path = "/" + obj.name + path;
  64. }
  65. return path;
  66. }
  67. }
  68. }