Unity学习记录-GameObject的内容

GameObject的成员变量

名字 name

  • 获取gameobject的名字

  • 为gameobject的名字赋值

    1
    2
    print(this.gameObject.name);//获取
    this.gameObject.name = "星辰微光";//赋值

判断是否激活 activeSelf

  • 获取物体是否激活

    1
    print(this.gameObject.activeSelf);

判断物体是否为静态对象 isStatic

  • 判断物体是否为静态对象

    1
    print(this.gameObject.isStatic);

获取物体所在的层级 layer

  • 返回的是一个int值,表示物体所在的层级

    1
    print(this.gameObject.layer);

获取物体的标签 tag

  • 返回一个string

    1
    print(this.gameObject.tag);

GameObject的静态方法

创建自带的几何体 CreatePrimitive

  • 参数为一个枚举值,表示各种几何体

    1
    2
    GameObject gameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
    gameObject.name = "我创建的几何体";

查找对象

  • 无法查找到失活的对象
  • 如果场景中有多个满足条件的对象,则查找是随机的

利用名字查找

  • 效率比较低,因为要遍历整个场景

    1
    2
    3
    4
    5
    GameObject gameObject1 = GameObject.Find("我创建的几何体");
    if(gameObject1!=null)
    {
    print(gameObject1.name);
    }//效率比较低,因为要遍历场景

利用tag查找

  • 查找单个
1
GameObject gameObject2 = GameObject.FindGameObjectWithTag("Player");
  • 查找多个
1
GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("Player");

实例化对象(克隆对象)

  • 可以是场景中已有的对象,或者是预制体对象。一般是克隆预制体对象

    1
    2
    GameObject.Instantiate(gameObject);
    //变量名是GameObject类,一般使用public从外部关联预制体

删除对象

  • 单纯的Destroy会在下一帧才真正删除并完成内存的释放。这样是为了防止卡顿

  • Dsetroy可以有两个参数,第一个参数为待删除物体,第二个参数是延迟几秒删除

  • Destroy还可以删除脚本

    1
    GameObject.Destroy(gameObject,5);//第二个参数代表延迟几秒钟删除
    1
    Destroy(this);//删除脚本
  • 利用DestroyImmediate可以实现立刻删除

    1
    DestroyImmediate(this.gameObject);//立刻删除

切换场景时不删除物体

  • 默认情况下,切换场景会删除场景中的所有物体

  • DontDestroyOnLoad实现切换场景时不删除物体

    1
    2
    GameObject.DontDestroyOnLoad(this.gameObject);
    //自己依附的对象过场景时不移除

GameObject的成员方法

创建一个空物体

  • 参数:名称,挂载的脚本
1
GameObject g2 = new GameObject("物体2", typeof(Lesson2),typeof(Lesson3));

获取挂载的脚本,这个在MonoBehaviour中也有

1
Lesson3 le3 = this.GetComponent<Lesson3>();

为对象添加脚本

  • 返回的是添加的脚本的一个对象
1
2
3
Lesson2 le2 = this.gameObject.AddComponent(typeof(Lesson2)) as Lesson2;

this.gameObject.AddComponent<Lesson3>();//泛型,推荐使用

设置激活失活

1
this.gameObject.SetActive(false);

标签的比较

  • 两种方法
  • 第一种是用CompareTag进行比较
  • 第二种是获取tag,然后进行判断
1
2
3
4
5
6
7
8
9
if(this.gameObject.CompareTag("Player"))
{
print("YES");
}

if(this.gameObject.tag=="Player")
{
print("YES");
}