按 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 内。
出于性能原因,建议不要每帧都使用此函数。
常见模式是将 GameObject 分配到 MonoBehaviour.Start 内的变量,然后在 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); } }
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.