查找对象

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

转载于:https://www.cnblogs.com/yueqingli/p/10625065.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值