天天看點

Unity查找物體的四大主流方法及差別

Unity查找物體的四大主流方法及差別

GameObject.Find()

Transform.Find()

GameObject.FindGameObjectsWithTag()

FindObjectsOfType()

不少新人在剛接觸unity查找物體的方法時,因為沒有認識到幾種查找物體方法它們之間的差別,而遇到bug 即“空引用異常”報錯,我在這裡說明一下它們的差別,供大家參考。同時這幾種方法也沒有絕對的好與壞,每種方法都有其适合使用的一些情況。

優點:

使用簡單友善

不會因為重名而報錯,同時查找的是自上而下的第一個物體

缺點

不能查找被隐藏的物體,否則出現“空引用異常”,這是很多新人在查找出現空引用bug的原因。

全局查找(周遊查找),查找效率低,很消耗性能。

代碼示範:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class GameObjectFind : MonoBehaviour {

private GameObject thing;

void Start () {

    thing = GameObject.Find("C4");
    thing.name = "thing";
    
}           

}

Transform.Find(),通過Transform元件查找子物體。

用這個方法查找物體時,根節點一定要處于“顯示”狀态,不能被隐藏。

用它查找孫物體及孫孫物體,一定要使用“絕對路徑”,否則出現“空引用異常”。

public class TransformFind : MonoBehaviour {

private Transform m_Transform;
private GameObject one;
private GameObject two;

void Start () {

    m_Transform = gameObject.GetComponent<Transform>();
    one = m_Transform.Find("D2").gameObject;
    two = m_Transform.Find("D2/D3").gameObject;

    Debug.Log(one.name);
    Debug.Log(two.name);

}           

GameObject.FindGameObjectWithTag()和GameObject.FindGameObjectsWithTag(),通過Tag标簽查找物體。

GameObject.FindGameObjectsWithTag():通過Tag标簽查找到一組物體,傳回一個數組。

GameObject.FindGameObjectWithTag():查找到這類tag标簽,自上而下第一個物體。

public class TagFind : MonoBehaviour {

private GameObject thing;
private GameObject[] things;
void Start () {

    things = GameObject.FindGameObjectsWithTag("Player");
    thing = GameObject.FindGameObjectWithTag("Player");

    Debug.Log(things.Length);
    Debug.Log(thing.name);
    
}               

FindObjectsOfTypeAll():傳回指定類型的對象清單。

public class FindObjectOfType : MonoBehaviour {

private GameObject[] things;
private GameObject thing;

void Start () {

    things = FindObjectsOfType<GameObject>();
    thing = FindObjectOfType<GameObject>();

    Debug.Log("第一個" + thing.name);
    for(int i = 0; i < things.Length; i++)
    {
        Debug.Log(things[i].name);
    }    
}           

其他方法

有一種方法,即使根節點被隐藏也能查找,大家自行百度。

喜歡的話可以關注我!别忘了點贊哦

作者:遊戲人TH

來源:CSDN

原文:

https://blog.csdn.net/qq_43157993/article/details/90411994

版權聲明:本文為部落客原創文章,轉載請附上博文連結!

繼續閱讀