unity 四 GameObject

GameObject 下有三个比较常用的方法:

1、GameObject.Find

GameObject.Find(string name),参数为字符串类型,找到的是游戏对象的 name,比如下面的 plan。返回的是一个 GameObject

GameObject a = GameObject.Find("Sphere")//从整个场景中找 name 为 Sphere 的游戏对象,如果有多个重复只会找到一个
  GameObject c = GameObject.Find("Sphere1/Sphere");//可以跟一个路径
        print(c.transform.position);

在这里插入图片描述

2、GameObject.FindWithTag

GameObject.FindWithTag(string tag),参数为字符串类型,找到的是游戏对象的 tag,返回一个 GameObject,如果存在多个,只会找到一个。

GameObject a = GameObject.FindWithTag("Finish");//
        if(a==null){}else{
            print(a.transform.position);
            print(a.name);
        }

3、GameObject.FindGameObjectsWithTag

GameObject[] FindGameObjectsWithTag(string tag);参数为字符串,返回一个数组类型的 GameObject。下面还粘贴了如何遍历对象数组。

GameObject[] b = GameObject.FindGameObjectsWithTag("ball");
        print(b.Length);
        if(b.Length==2){
            print("2个为 ball 的游戏对象");
        }
        for (int i = 0; i < b.Length;i++){
            print(b[i].name);
        }
        foreach(GameObject item in b){
            print("foreach:" + item.name);
        }

tag 在哪,如何添加??

1、tag 的位置
在这里插入图片描述
2、 设置游戏的 tag
1、点击Add Tag
在这里插入图片描述
2、点击加号,输入框中输入名字,然后保存,就添加了 Tag。在tag 的位置的地方就会多一个 tag 的选择。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u014196765/article/details/88925047
今日推荐