GameObject.Find與Transform.Find的區別


1.GameObject.Find

函數原型: 

public static  GameObject  Find(string name);
說明:1.GameObject只能查找到active的物體
   2.如果name指定路徑,則按路徑查找;否則遞歸查找,直到查找到第一個符合條件的GameObject或者返回null
 
2.transform.Find
函數原型:
 
public  Transform  Find(string n);
說明:1.transform.Find用於查找子節點,它並不會遞歸的查找物體,也就是說它只會查找它的子節點,並不會查找子節點的子節點。
用代碼驗證:
 1 public class TestFind : MonoBehaviour
 2 {
 3    
 4    public string name = "";
 5    private void Start()
 6    {
 7       Transform t = transform.Find(name);
 8       if(t != null)
 9          print("找到了");
10       else
11       {
12          print("沒找到");
13       }
14    }
15 }

說明:TestFind腳本掛在GameObject物體上。

1.name為a, 輸出找到了

2.name為aa,輸出沒找到

3.name為b,輸出找到了

4.name為bb,輸出沒找到

 

補充:在實際開發中可能遇到這樣的情況,給定一個節點,在這個子節點中遞歸的查找符合條件的節點。transform.Find不能遞歸查找,不能直接使用,GameObject.Find又做了很多無用功,關鍵若是重名還不一定能滿足需求。於是我們可以自己寫一個遞歸程序:

 1  public static Transform FindChildRecursively(Transform parent, string name)
 2         {
 3             Transform t = null;
 4             t = parent.Find(name);
 5             if (t == null)
 6             {
 7                 foreach (Transform tran in parent)
 8                 {
 9                    t =  FindChildRecursively(tran, name);
10                    if (t != null)
11                    {
12                        return t;
13                    }
14                 }
15             }
16 
17             return t;
18         }
19     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM