Unity查找物体的四大主流方法及区别
Game .Find()
Transform.Find()
Game .FindGame sWithTag()
Find sOfType()

不少新人在刚接触unity查找物体的方法时,因为没有认识到几种查找物体方法它们之间的区别,而遇到bug 即“空引用异常”报错,我在这里说明一下它们的区别,供大家参考。同时这几种方法也没有绝对的好与坏,每种方法都有其适合使用的一些情况。

Game .Find()
优点:

使用简单方便
不会因为重名而报错,同时查找的是自上而下的第一个物体
缺点

不能查找被隐藏的物体,否则出现“空引用异常”,这是很多新人在查找出现空引用bug的原因。
全局查找(遍历查找),查找效率低,很消耗性能。
代码演示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Game Find : MonoBehaviour {

private Game  thing;void Start () {    thing = Game .Find("C4");    thing.name = "thing";    }

}

Transform.Find(),通过Transform组件查找子物体。
用这个方法查找物体时,根节点一定要处于“显示”状态,不能被隐藏。
用它查找孙物体及孙孙物体,一定要使用“绝对路径”,否则出现“空引用异常”。
代码演示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformFind : MonoBehaviour {

private Transform m_Transform;private Game  one;private Game  two;void Start () {    m_Transform = game .GetComponent<Transform>();    one = m_Transform.Find("D2").game ;    two = m_Transform.Find("D2/D3").game ;    Debug.Log(one.name);    Debug.Log(two.name);}

}

Game .FindGame WithTag()和Game .FindGame sWithTag(),通过Tag标签查找物体。
Game .FindGame sWithTag():通过Tag标签查找到一组物体,返回一个数组。
Game .FindGame WithTag():查找到这类tag标签,自上而下第一个物体。

代码演示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TagFind : MonoBehaviour {

private Game  thing;private Game [] things;void Start () {    things = Game .FindGame sWithTag("P ");    thing = Game .FindGame WithTag("P ");    Debug.Log(things.Length);    Debug.Log(thing.name);    }    

}

Find sOfType()
Find sOfTypeAll():返回指定类型的对象列表。

代码演示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Find OfType : MonoBehaviour {

private Game [] things;private Game  thing;void Start () {    things = Find sOfType<Game >();    thing = Find OfType<Game >();    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
版权声明:本文为博主原创文章,转载请附上博文链接!

收藏 打印