Unity几种查找物体的方法

xiaoxiao2021-02-28  124

Unity版本为5.3.2

在脚本中查找游戏物体是非常常见的,这里列一些查找方法


首先是Transform下面的

using UnityEngine; using System.Collections; public class Communicate : MonoBehaviour { // Use this for initialization void Start () { Transform name1 = transform.Find ("GameObject/name");//使用transform.find只能查询自身下一级的子物体,且子物体是否激活都能查到,若查询多级的子物体则加'/',hierarchy的路径 Transform name2 = transform.FindChild("name");//这个跟transform.find一样 print(name1); print(name2); } // Update is called once per frame void Update () { } }

GameObject下面的

using UnityEngine; using System.Collections; public class Communicate : MonoBehaviour { // Use this for initialization void Start () { GameObject name1 = GameObject.Find("name");//能查询,hierarchy中所有的物体,但是必须是激活的 GameObject name2 = GameObject.FindGameObjectWithTag("name");//根据tag查找物体,但是必须是激活的 GameObject[] name3 = GameObject.FindGameObjectsWithTag("name");//根据tag查找同一tag的物体,但是必须是激活的 } // Update is called once per frame void Update () { } }

这里注意出于性能原因,建议不要每帧使用GameObject.Find(),而应在启动时将结果缓存到成员变量中,或使用GameObject.FindWithTag。


Object下面的

using UnityEngine; using System.Collections; public class Communicate : MonoBehaviour { // Use this for initialization void Start () { Transform name1 = FindObjectOfType(typeof(Transform))as Transform;//在hierarchy中查找有transform组件的物体,必须是激活的 Transform[] name = FindObjectsOfType(typeof(Transform))as Transform[];//在hierarchy中查找有transform组件的物体,必须是激活的 } // Update is called once per frame void Update () { } }

这里需要注意一点,使用这个方法很慢


转载请注明原文地址: https://www.6miu.com/read-33608.html

最新回复(0)