/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Meta.WitAi.Utilities
{
public static class GameObjectSearchUtility
{
///
/// Finds the first available scene scripts of a specific object type
///
/// Whether inactive GameObjects should be searched
/// Script type being searched
/// The first found script matching the specified type
public static T FindSceneObject(bool includeInactive = true) where T : UnityEngine.Object
{
T[] results = FindSceneObjects(includeInactive, true);
return results == null || results.Length == 0 ? null : results[0];
}
///
/// Finds all scene scripts of a specific object type
///
/// Whether inactive GameObjects should be searched
/// Whether the method should return as soon as a matching script is found
/// Script type being searched
/// All scripts matching the specified type
public static T[] FindSceneObjects(bool includeInactive = true, bool returnImmediately = false) where T : UnityEngine.Object
{
// Use default functionality
if (!includeInactive)
{
return GameObject.FindObjectsOfType();
}
// Get results
List results = new List();
// Iterate loaded scenes
for (int s = 0; s < SceneManager.sceneCount; s++)
{
// Iterate root
foreach (var rootGameObject in SceneManager.GetSceneAt(s).GetRootGameObjects())
{
T[] children = rootGameObject.GetComponentsInChildren(includeInactive);
if (children != null && children.Length > 0)
{
results.AddRange(children);
if (returnImmediately)
{
return results.ToArray();
}
}
}
}
// Return all
return results.ToArray();
}
}
}