GameObjectSearchUtility.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. using System.Collections.Generic;
  9. using UnityEngine;
  10. using UnityEngine.SceneManagement;
  11. namespace Meta.WitAi.Utilities
  12. {
  13. public static class GameObjectSearchUtility
  14. {
  15. /// <summary>
  16. /// Finds the first available scene scripts of a specific object type
  17. /// </summary>
  18. /// <param name="includeInactive">Whether inactive GameObjects should be searched</param>
  19. /// <typeparam name="T">Script type being searched</typeparam>
  20. /// <returns>The first found script matching the specified type</returns>
  21. public static T FindSceneObject<T>(bool includeInactive = true) where T : UnityEngine.Object
  22. {
  23. T[] results = FindSceneObjects<T>(includeInactive, true);
  24. return results == null || results.Length == 0 ? null : results[0];
  25. }
  26. /// <summary>
  27. /// Finds all scene scripts of a specific object type
  28. /// </summary>
  29. /// <param name="includeInactive">Whether inactive GameObjects should be searched</param>
  30. /// <param name="returnImmediately">Whether the method should return as soon as a matching script is found</param>
  31. /// <typeparam name="T">Script type being searched</typeparam>
  32. /// <returns>All scripts matching the specified type</returns>
  33. public static T[] FindSceneObjects<T>(bool includeInactive = true, bool returnImmediately = false) where T : UnityEngine.Object
  34. {
  35. // Use default functionality
  36. if (!includeInactive)
  37. {
  38. return GameObject.FindObjectsOfType<T>();
  39. }
  40. // Get results
  41. List<T> results = new List<T>();
  42. // Iterate loaded scenes
  43. for (int s = 0; s < SceneManager.sceneCount; s++)
  44. {
  45. // Iterate root
  46. foreach (var rootGameObject in SceneManager.GetSceneAt(s).GetRootGameObjects())
  47. {
  48. T[] children = rootGameObject.GetComponentsInChildren<T>(includeInactive);
  49. if (children != null && children.Length > 0)
  50. {
  51. results.AddRange(children);
  52. if (returnImmediately)
  53. {
  54. return results.ToArray();
  55. }
  56. }
  57. }
  58. }
  59. // Return all
  60. return results.ToArray();
  61. }
  62. }
  63. }