うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】全シーンのすべてのオブジェクトを取得する

コード

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public static class SceneUtil
{
    public static List<GameObject> GetAllSceneObjects()
    {
        var objs = new List<GameObject>(100);
        var count = SceneManager.sceneCount;
        for (var i = 0; i < count; i++)
        {
            var scene = SceneManager.GetSceneAt(i);
            foreach (var obj in scene.GetRootGameObjects())
            {
                FindRecursive(ref objs, obj);
            }
        }

        return objs;
    }
 
    private static void FindRecursive(ref List<GameObject> list, GameObject root)
    {
        list.Add(root);
        foreach (Transform child in root.transform)
        {
            FindRecursive(ref list, child.gameObject);
        }
    }
}

使い方

var sceneObjects = GetAllSceneObjects();
 
// 全部の中から、Testがつくオブジェクトを探す 
sceneObjects.Where(o => o.name.Contains("Test"));