Unity 获取场景中所有目标对象(包括不激活的对象)

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    // 获取场景中所有目标对象(包括不激活的对象)不包括Prefabs:

    List<T> FindSceneObject<T>(string _SceneName)where T:UnityEngine.Component {
        List<T> objectsInScene = new List<T>();
        foreach (var go in Resources.FindObjectsOfTypeAll<T>())
        {
            if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave)
                continue;
            if (EditorUtility.IsPersistent(go.transform.root.gameObject))// 如果对象位于Scene中,则返回false
                continue;
            if (_SceneName != go.gameObject.scene.name)
                continue;
            Debug.LogFormat("gameObject:{0},scene:{1}", go.gameObject.name, go.gameObject.scene.name);
            objectsInScene.Add(go);
        }
        return objectsInScene;
    }
}

参考:Resources.FindObjectsOfTypeAll

posted @ 2019-04-27 05:51  落樱的凄美  阅读(3025)  评论(0编辑  收藏  举报