Unity查找物体的四大主流方法及区别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Unity查找物体的四大主流方法及区别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2053字,纯文字阅读大概需要3分钟。
内容图文
优点:
使用简单方便
不会因为重名而报错,同时查找的是自上而下的第一个物体
缺点
不能查找被隐藏的物体,否则出现“空引用异常”,这是很多新人在查找出现空引用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";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Transform.Find(),通过Transform组件查找子物体。
用这个方法查找物体时,根节点一定要处于“显示”状态,不能被隐藏。
用它查找孙物体及孙孙物体,一定要使用“绝对路径”,否则出现“空引用异常”。
代码演示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
GameObject.FindGameObjectWithTag()和GameObject.FindGameObjectsWithTag(),通过Tag标签查找物体。
GameObject.FindGameObjectsWithTag():通过Tag标签查找到一组物体,返回一个数组。
GameObject.FindGameObjectWithTag():查找到这类tag标签,自上而下第一个物体。
代码演示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
FindObjectsOfType()
FindObjectsOfTypeAll():返回指定类型的对象列表。
代码演示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindObjectOfType : MonoBehaviour {
private GameObject[] things;
private GameObject thing;
void Start () {
things = FindObjectsOfType<GameObject>();
thing = FindObjectOfType<GameObject>(http://www.my516.com);
Debug.Log("第一个" + thing.name);
for(int i = 0; i < things.Length; i++)
{
Debug.Log(things[i].name);
}
}
}
---------------------
原文:https://www.cnblogs.com/ly570/p/11044514.html
内容总结
以上是互联网集市为您收集整理的Unity查找物体的四大主流方法及区别全部内容,希望文章能够帮你解决Unity查找物体的四大主流方法及区别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。