Skip to content

Instantly share code, notes, and snippets.

@darktable

darktable/Helper.cs

Created Jun 8, 2019
Embed
What would you like to do?
A utility script to find every component of a particular type in a scene. Not sure what the results will be if you have multiple additive scenes loaded.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Helper : MonoBehaviour
{
public static List<T> FindThemAll<T>(bool includeInactive = false) where T : UnityEngine.Component
{
var scene = SceneManager.GetActiveScene();
var rootObjects = scene.GetRootGameObjects();
var results = new List<T>();
foreach (var go in rootObjects)
{
var found = go.GetComponentsInChildren<T>(includeInactive);
if (found.Length > 0)
{
results.AddRange(found);
}
}
return results;
}
// Start is called before the first frame update
void Start()
{
var test = FindThemAll<AudioSource>(true);
// This should spew the name of every gameobject with an audiosource attached.
foreach (var tf in test)
{
Debug.LogFormat("found: {0}", tf.name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment