//1
void GetRoot()
{
List<GameObject> allGOs = new List<GameObject>();
GameObject[] rootGOs = gameObject.scene.GetRootGameObjects();
for (int i = 0; i < rootGOs.Length; i++)
GetAllChildren(rootGOs[i].transform, allGOs);
all = allGOs;
}
void GetAllChildren(Transform current, List<GameObject> arrayToFill)
{
arrayToFill.Add(current.gameObject);
for (int i = 0; i < current.childCount; i++)
GetAllChildren(current.GetChild(i), arrayToFill);
}
//2
private List<GameObject> GetAllSceneObjectsWithInactive()
{
var allTransforms = Resources.FindObjectsOfTypeAll(typeof(Transform));
var previousSelection = Selection.objects;
Selection.objects = allTransforms.Cast<Transform>()
.Where(x => x != null)
.Select(x => x.gameObject)
.Where(x => x != null && !x.activeInHierarchy)
.Cast<UnityEngine.Object>().ToArray();
var selectedTransforms = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
Selection.objects = previousSelection;
return selectedTransforms.Select(tr => tr.gameObject).ToList();
}
写成了一个扩展方法
using UnityEngine;
using System.Collections;
using System.Linq;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public static class Extool
{
//1
public static void GetGO(this GameObject self,ref GameObject go, string name)
{
GameObject[] rootGOs = self.scene.GetRootGameObjects();
for (int i = 0; i < rootGOs.Length; i++)
GetAllChildren(rootGOs[i].transform, ref go, name);
}
public static void GetAllChildren(Transform current, ref GameObject go, string name)
{
if (current.name == name)
{
go = current.gameObject;
return;
}
for (int i = 0; i < current.childCount; i++)
GetAllChildren(current.GetChild(i), ref go, name);
}
//2
public static void GetAllSceneObjectsWithInactive(this MonoBehaviour self,ref GameObject go,string name)
{
var allTransforms = Resources.FindObjectsOfTypeAll(typeof(Transform));
List<GameObject> allGOs = new List<GameObject>();
allGOs = allTransforms.Cast<Transform>()
.Where(x => x != null)
.Select(x => x.gameObject)
//.Where(x => x != null && !x.activeInHierarchy)
.Where(x => x != null && x.scene == SceneManager.GetActiveScene())
.Cast<UnityEngine.GameObject>().ToList();
for (int i = 0; i < allGOs.Count; i++)
{
if (allGOs[i].name==name)
{
go = allGOs[i];
break;
}
}
}
}
Unity场景对象检索
本文介绍两种在Unity中获取场景内所有游戏对象的方法,包括活动和非活动对象。第一种方法递归地遍历所有根对象及其子对象。第二种方法使用资源查找及选择工具,筛选出特定场景中的游戏对象。
4004

被折叠的 条评论
为什么被折叠?



