纯粹是为了记载下来防止忘记,没什么技术含量。顾名思义,该函数就是按照游戏类型来查找游戏对象。
首先来看Unity Manual手册:https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
public static Object FindObjectOfType(Type type);
type | The type of object to find. |
Returns
Object This returns the Object that matches the specified type. It returns null if no Object matches the type
Description
Returns the first active loaded object of Type type
.
::ref::.FindObjectOfType will return no Assets (meshes, textures, prefabs, ...) or inactive objects. It is used to locate a GameObject This does not return an Object that has HideFlags.DontSave set.
This method calls Object.FindObjectOfType and returns the object that matches the type and null if no object matches the type.
Please note that this function is very slow. It is not recommended to use this function every frame. In most cases you can use the singleton pattern instead.
意思就是返回和type一样的被激活的物体。至于顺序可以看此博客:
https://www.cnblogs.com/Peng18233754457/p/8966458.html
手册里给出的示例代码GUITexture已经被弃用,所以此处实验代码如下:
using UnityEngine;
using System.Collections;
// Search for any object of Type ScriptExample ,
// if found print its name, else print a message
// that says that it was not found.
public class ExampleClass : MonoBehaviour
{
void Start()
{
ScriptExample se = GameObject.FindObjectOfType<ScriptExample>();
if (se)
Debug.Log("ScriptExample object found: " + se.name);
else
Debug.Log("No ScriptExample object could be found");
}
}
其中这两个cs文件都挂载到了Camera上。