按 name
查找 GameObject,然后返回它。
此函数仅返回活动 GameObject。如果未找到具有 name
的 GameObject,则返回 null。如果 name
包含“/”字符,则会向路径名称那样遍历此层级视图。
出于性能原因,建议不要每帧都使用此函数,而是在启动时将结果缓存到成员变量中,或者使用 GameObject.FindWithTag。
注意:如果您要查找子 GameObject,使用 Transform.Find 通常会更加轻松。
注意:如果正在使用多个场景运行此游戏,则 Find 将在所有这些场景中进行搜索。
using UnityEngine; using System.Collections;
// This returns the GameObject named Hand in one of the Scenes.
public class ExampleClass : MonoBehaviour { public GameObject hand;
void Example() { // This returns the GameObject named Hand. hand = GameObject.Find("Hand");
// This returns the GameObject named Hand. // Hand must not have a parent in the Hierarchy view. hand = GameObject.Find("/Hand");
// This returns the GameObject named Hand, // which is a child of Arm > Monster. // Monster must not have a parent in the Hierarchy view. hand = GameObject.Find("/Monster/Arm/Hand");
// This returns the GameObject named Hand, // which is a child of Arm > Monster. hand = GameObject.Find("Monster/Arm/Hand"); } }
GameObject.Find 有助于在加载时自动连接对其他对象的引用;例如在 MonoBehaviour.Awake 或 MonoBehaviour.Start 内。
出于性能原因,建议不要每帧都使用此函数。
A common pattern is to assign a GameObject to a variable inside MonoBehaviour.Start, and use the variable in MonoBehaviour.Update.
using UnityEngine; using System.Collections;
// Find the GameObject named Hand and rotate it every frame
public class ExampleClass : MonoBehaviour { private GameObject hand;
void Start() { hand = GameObject.Find("/Monster/Arm/Hand"); }
void Update() { hand.transform.Rotate(0, 100 * Time.deltaTime, 0); } }