Unity中提供了五种获取对象的方法
1.通过对象名称(Find)
public static GameObject Find(string name);
通过名字寻找对象并返回它,只返回active GameObject,如果没有GameObject,则返回null。如果名称内包含“/”字符,会当做是hierarchy中的一个路径名。
2.通过标签获取单个游戏对象
public static GameObject FindWithTag(string tag))
返回一个用tag做标识的活动的对象,如果没有找到则为null。
1 using UnityEngine; 2 using System.Collections; 3 4 public class findwithtag : MonoBehaviour { 5 public GameObject a; 6 public GameObject b; 7 void Start() { 8 if (b == null) 9 b = GameObject.FindWithTag("Respawn"); 10 11 Instantiate(a, b.transform.position, b.transform.rotation); 12 } 13 } 14 复制代码
3.通过标签获取多个游戏对象
public static GameObject[] FindGameObjectsWithTag(string tag);
返回一个用对象标记的标签,如果没有找到对象则返回空数组。
1 using UnityEngine; 2 using System.Collections; 3 4 public class Example : MonoBehaviour { 5 public GameObject a; 6 public GameObject[] b; 7 void Start() { 8 if (b == null) 9 b = GameObject.FindGameObjectsWithTag("Respawn"); 10 11 foreach (GameObject respawn in b) { 12 Instantiate(a, respawn.transform.position, respawn.transform.rotation); 13 } 14 } 15 }
4.通过类型获取单个游戏对象
返回类型为type的活动的第一个游戏对象。
5.通过类型获取多个游戏对象
返回类型为type的所有活动的游戏对象列表。
4.2添加子对象
public static GameObject CreatePrimitive(PrimitiveType type);
创建一个游戏对象与原始网格渲染器和适当的collider。
1 using UnityEngine; 2 using System.Collections; 3 4 public class example : MonoBehaviour { 5 void Start() { 6 GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane); 7 GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); 8 cube.transform.position = new Vector3(0, 0.5F, 0); 9 GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); 10 sphere.transform.position = new Vector3(0, 1.5F, 0); 11 GameObject capsule = GameObject.CreatePrimitive(PrimitiveType.Capsule); 12 capsule.transform.position = new Vector3(2, 1, 0); 13 GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder); 14 cylinder.transform.position = new Vector3(-2, 1, 0); 15 } 16 }
4.3遍历对象树
foreach (Transform child in transform) {
Debug.Log(child.gameObject.name);
}
4.4清除所有子对象
foreach (Transform child in transform) {
Destroy(child.gameObject);
}
文章引用来源:https://blog.csdn.net/s1314_JHC/article/details/80811834
文章引用来源:https://www.cnblogs.com/xieyuanzhen-Feather/p/6591240.html