Skip to content

Instantly share code, notes, and snippets.

@darktable
Created June 8, 2019 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darktable/1819e126b0abd3b8a5afc6fcedcf7645 to your computer and use it in GitHub Desktop.
Save darktable/1819e126b0abd3b8a5afc6fcedcf7645 to your computer and use it in GitHub Desktop.
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