How to get all GameObjects in Scene?

I need to get every single game object in the current scene in a GameObject using C#… Any ideas? Thanks in advance! :slight_smile:

I have found that FindObjectOfType will return all kinds of weird things that are not in the scene. “activeInHeirachy” solves the problem:

GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>() ;
foreach(object go in allObjects)
   if (go.activeInHierarchy)
      print(thisObject+" is an active object") ;

You could try either of these:

GameObject.FindObjectsOfType(typeof(MonoBehaviour)); //returns Object[]
GameObject.FindGameObjectsWithTag("Untagged");  //returns GameObject[]

// get root objects in scene
List rootObjects = new List();
Scene scene = SceneManager.GetActiveScene();
scene.GetRootGameObjects( rootObjects );

// iterate root objects and do something
for (int i = 0; i < rootObjects.Count; ++i)
{
	GameObject gameObject = rootObjects[ i ];
	gameObject.DoSomething();
}

The Unity documentation for Resources.FindObjectsOfTypeAll has this example:

// This script finds all the objects in scene, excluding prefabs:

List<GameObject> GetAllObjectsInScene()
{
    List<GameObject> objectsInScene = new List<GameObject>();

    foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[])
    {
        if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave)
            continue;

        if (!EditorUtility.IsPersistent(go.transform.root.gameObject))
            continue;

        objectsInScene.Add(go);
    }

    return objectsInScene;
}

C# code:

Transform[] hinges =GameObject.FindObjectsOfType(typeof(Transform)) as Transform[];

javaScript Code:

var hinges :Transform[] = FindObjectsOfType(Transform) as Transform[];

Here’s what I did without using Resources.FindObjectsOfTypeAll

Also unlike FindObjectsOfTypeAll, this one returns the array elements in a parent->children order.

Edit: Replaced main foreach loops with for loops for better performance.

    void Start()
    {
        List<GameObject> allGOs = new List<GameObject>();
        GameObject[] rootGOs = gameObject.scene.GetRootGameObjects();

        for (int i = 0; i < rootGOs.Length; i++)
            GetAllChildren(rootGOs*.transform, allGOs);*

//Print them all out
foreach (GameObject g in allGOs)
Debug.Log(g.name);
}

void GetAllChildren(Transform current, List arrayToFill)
{
arrayToFill.Add(current.gameObject);

for (int i = 0; i < current.childCount; i++)
GetAllChildren(current.GetChild(i), arrayToFill);
}

Example and Documentation done by myself, code was written by the help of Chat-GPT, then I modified it.

namespace User.Defined
{
    using System;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;


    /// <summary>
    ///     A <see langword="static"/> <see langword="class"/> providing extension methods to enhance
    ///     one's experience in Unity GameDev projects.
    /// </summary>
    internal static class CustomExtensionMethods
    {
        /// <summary>
        ///     Retrieves <i>every single</i> <see cref="Transform"/> in a given <see cref="Scene"/>.
        /// </summary>
        /// <param name="self">
        ///     This parameter is the current <see cref="Scene"/> instance.
        /// </param>
        /// <returns>
        ///     A <see cref="Transform"/> <see cref="Array"/> comprehending <i>all</i>
        ///     <see cref="Transform"/>s available in the <see cref="Scene"/> in question.
        /// </returns>
        internal static GameObject[] GetAllGameObjectsInHierarchy(this Scene self)
        {
            var roots = self.GetRootGameObjects();

            var transList = new List<GameObject>();

            for (var i = 0; i < roots.Length; i++)
                transList.AddRange(roots*.GetSelfAndDescendants());*

return transList.ToArray();
}

///


/// Finds each in a given root.
///

///
/// Note: this method does not only get any possible parent, but also all of its children
///
and if a given child found to be a parent itself, the loop goes on…
///
/// For further details, check the following link out:
///

///
///
///
/// The originating source currently using the method.
///
///
/// An of any on this
/// .
///
internal static GameObject[] GetSelfAndDescendants(this GameObject self)
{
var transforms = self.GetComponentsInChildren(includeInactive: true);

var gameObjectList = new List(transforms.Length);

for (var i = 0; i < transforms.Length; i++)
gameObjectList.Add(transforms*.gameObject);*

return gameObjectList.ToArray();
}
}
}
Usage example:
using UnityEngine;
using UnityEngine.SceneManagement;
using User.Defined;

// NOTE: This shoud be attached to a GameObject as a C# file named: ShowCase
internal class ShowCase : MonoBehaviour
{
[SerializeField]
private bool entireScene = true;

private void Awake()
{
if (entireScene) EntireSceneScoped();

else GameObjectScoped();
}

private void EntireSceneScoped()
{
foreach (var gameObject in SceneManager.GetActiveScene().GetAllGameObjectsInHierarchy())
// TODO: Your own code here instead…
print(gameObject.name);
}

private void GameObjectScoped()
{
foreach (var gameObject in gameObject.GetSelfAndDescendants())
// TODO: Your own code here instead…
print(gameObject.name);
}
}

Transform arrTransforms = Resources.FindObjectsOfTypeAll().Where((s) => (s.hideFlags == HideFlags.None)).ToArray();