Transform.Find
Declaration
public Transform Find(string n);Параметры
| Параметр | Описание |
|---|---|
| n | Строка поиска, либо имя непосредственного дочернего объекта, либо путь в иерархии для поиска потомка. |
Возвращаемое значение
Transform Найденное дочернее преобразование. Null, если дочернее с соответствующим именем не найдено.
Описание
Находит дочернюю структуру по имени n и возвращает ее.
Если нет ребенка с именем n не найдено, возвращается null. Если n содержит символ '/', он будет доступен Transform в иерархии как имя пути.
Примечание: Find работает неправильно, если в имени файла есть '/' GameObject.
Примечание: Find не выполняет рекурсивное спуск вниз по Transform иерархии.
Примечание: Find можно найти трансформацию инвалидов GameObject.
using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { public GameObject player; public Transform gun; public Transform ammo;
//Invoked when a button is clicked. public void Example() { //Finds and assigns the child named "Gun". gun = player.transform.Find("Gun");
//If the child was found. if (gun != null) { //Find the child named "ammo" of the gameobject "magazine" (magazine is a child of "gun"). ammo = gun.transform.Find("magazine/ammo"); } else Debug.Log("No child with the name 'Gun' attached to the player"); } }
Как описано Find не спускается Transform иерархии. Find будет искать только в данном списке детей, ищущих именованного Transform. В следующем примере показан результат Find ищу GameObjects. Название каждого GameObject используется в Find. Вот почему два GameObjects на одном и том же уровне иерархии обнаруживаются и сообщаются.
A GameObject с тремя детьми. Find() не находит третьего ребенка.
// ExampleClass has a GameObject with three spheres attached. // Two of these are children of the GameObject. The third // transform, sphere3, is a child of sphere2. Find() does // not find this child.
using UnityEngine;
public class ExampleClass : MonoBehaviour { void Start() { Transform result;
for (int i = 1; i < 4; i++) { string sph;
sph = "sphere" + i.ToString(); result = gameObject.transform.Find(sph);
if (result) { Debug.Log("Found: " + sph); } else { //Find() does not find sphere3 Debug.Log("Did not find: " + sph);
//But we can access it with '/' character or by using GetChild() Transform newresult; newresult = gameObject.transform.Find("sphere2/sphere3");
if (newresult) { Debug.Log("But now found:" + sph); } } } } }