Object.FindObjectsOfType

切换到手册
public static Object[] FindObjectsOfType (Type type);

参数

type要查找的对象类型。

返回

Object[] 找到的与指定类型匹配的对象的数组。

描述

返回所有类型为 type 的已加载的激活对象的列表。

该函数不返回任何资源(网格、纹理、预制件等)或非激活对象,也不返回设置了 HideFlags.DontSave 的对象。要避免这些限制,请使用 Resources.FindObjectsOfTypeAll

请注意,该函数的运行速度非常缓慢。不建议对每一帧都使用该函数。 在大多数情况下,您可以改为使用单例模式。

using UnityEngine;

// Ten GameObjects are created and have TextMesh components added. // When the game runs press the Space key and the number of // TextMesh components are displayed.

public class ScriptExample : MonoBehaviour { private const int count = 10;

void Start() { var gameObjects = new GameObject[count]; var expectedObjects = new TextMesh[count];

for (var i = 0; i < count; ++i) { gameObjects[i] = new GameObject(); expectedObjects[i] = gameObjects[i].AddComponent<TextMesh>(); } }

void Update() { if (Input.GetKeyDown(KeyCode.Space)) { var foundObjects = FindObjectsOfType<TextMesh>(); Debug.Log(foundObjects + " : " + foundObjects.Length); } } }