Unity版本为5.3.2
在脚本中查找游戏物体是非常常见的,这里列一些查找方法
using UnityEngine;
using System.Collections;
public class Communicate : MonoBehaviour {
void Start () {
Transform name1 = transform.Find (
"GameObject/name");
Transform name2 = transform.FindChild(
"name");
print(name1);
print(name2);
}
void Update () {
}
}
GameObject下面的
using UnityEngine;
using System.Collections;
public class Communicate : MonoBehaviour {
void Start () {
GameObject name1 = GameObject.Find(
"name");
GameObject name2 = GameObject.FindGameObjectWithTag(
"name");
GameObject[] name3 = GameObject.FindGameObjectsWithTag(
"name");
}
void Update () {
}
}
这里注意出于性能原因,建议不要每帧使用GameObject.Find(),而应在启动时将结果缓存到成员变量中,或使用GameObject.FindWithTag。
Object下面的
using UnityEngine;
using System.Collections;
public class Communicate : MonoBehaviour {
void Start () {
Transform name1 = FindObjectOfType(
typeof(Transform))
as Transform;
Transform[] name = FindObjectsOfType(
typeof(Transform))
as Transform[];
}
void Update () {
}
}
这里需要注意一点,使用这个方法很慢