FindInSceneProvider.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System.Linq;
  2. using System.Text.RegularExpressions;
  3. using UnityEngine;
  4. using Object = UnityEngine.Object;
  5. namespace LLM.Editor.Analysis
  6. {
  7. /// <summary>
  8. /// Provides a list of GameObjects found in the current scene based on a query.
  9. /// Supports searching by name (with wildcards), component type, or tag.
  10. /// </summary>
  11. public class FindInSceneProvider : IContextProvider
  12. {
  13. public class SceneQueryResult
  14. {
  15. public string name;
  16. public string id;
  17. }
  18. public object GetContext(Object target, string qualifier)
  19. {
  20. if (string.IsNullOrEmpty(qualifier))
  21. {
  22. return "Error: A query string (qualifier) is required for FindInScene (e.g., 'name: Player', 'component: Rigidbody', 'tag: Enemy').";
  23. }
  24. var gameObjects = Object.FindObjectsOfType<GameObject>();
  25. var queryParts = qualifier.Split(new[] { ':' }, 2);
  26. var queryType = queryParts[0].Trim().ToLower();
  27. var queryValue = queryParts.Length > 1 ? queryParts[1].Trim() : "";
  28. var results = gameObjects.AsQueryable();
  29. switch (queryType)
  30. {
  31. case "name":
  32. var pattern = WildcardToRegex(queryValue);
  33. results = results.Where(go => Regex.IsMatch(go.name, pattern, RegexOptions.IgnoreCase));
  34. break;
  35. case "component":
  36. var componentType = GetTypeByName(queryValue);
  37. if (componentType != null)
  38. {
  39. results = results.Where(go => go.GetComponent(componentType));
  40. }
  41. else
  42. {
  43. // If the type can't be found, return no results.
  44. results = Enumerable.Empty<GameObject>().AsQueryable();
  45. }
  46. break;
  47. case "tag":
  48. results = results.Where(go => go.CompareTag(queryValue));
  49. break;
  50. case "layer":
  51. results = results.Where(go => go.layer == LayerMask.NameToLayer(queryValue));
  52. break;
  53. default:
  54. return $"Error: Invalid query type '{queryType}'. Use 'name', 'component', or 'tag'.";
  55. }
  56. // Return a structured result with name and instance ID for each found object.
  57. return results.Select(go => new SceneQueryResult { name = go.name, id = go.GetInstanceID().ToString() }).ToList();
  58. }
  59. private static System.Type GetTypeByName(string typeName)
  60. {
  61. foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
  62. {
  63. var type = assembly.GetType(typeName);
  64. if (type != null) return type;
  65. }
  66. return null;
  67. }
  68. private static string WildcardToRegex(string value)
  69. {
  70. return "^" + Regex.Escape(value).Replace("\\*", ".*").Replace("\\?", ".") + "$";
  71. }
  72. }
  73. }