Find(string)
Finds and returns a GameObject with the specified name or hierarchy path.
Read time 3 minutesLast updated 5 days ago
Definition
- Type: Method
- Namespace: UnityEngine
- Assembly: UnityEngine.CoreModule
public static GameObject Find(string name)
Parameters
The name or hierarchy path of the GameObject to find.
Returns
Type | Description |
|---|---|
| GameObject |
Remarks
Only returns active GameObjects. Returns if no GameObject with exists. If contains a character, it is treated as a path to the GameObject in the Hierarchy window. If there are multiple GameObjects with the same name, the recommended best practice is to not use this method.
nullnamename/If a path starts with , the first object in the path must not have any parents in the Hierarchy view. Paths that don't start with a can start from a child GameObject. For example, if there is a GameObject named Hand which is a child of Arm which is a child of Monster, you can find it with or but not .
///Monster/Arm/HandArm/Hand/Arm/HandGameObject.FindFindThe more GameObjects you have and the more frequently you call , the greater the impact on your application's performance. Instead, cache the result in a member variable at startup, or use GameObject.FindWithTag.
GameObject.FindTo find a child GameObject, it's often preferable to use Transform.Find, which only searches the children of the specific transform rather than the whole scene.
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. // Monster can have a parent in the Hierarchy view. hand = GameObject.Find("Monster/Arm/Hand"); }}
GameObject.FindA 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 framepublic class ExampleClass : MonoBehaviour{ private GameObject hand; void Start() { hand = GameObject.Find("/Monster/Arm/Hand"); } void Update() { hand.transform.Rotate(0, 100 * Time.deltaTime, 0); }}
Additional Resources: GameObject.FindGameObjectsWithTag