我本来以为unity里的Gameobject类就是一个正常的类,生命周期和正常的类一样,结果发现不是的。
unity里如果你在脚本里的某个函数里定义一个Gameobject,它不会作为一个局部变量随着函数的终止而自动销毁。如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour {
void CreateAnEmpty()
{
GameObject a = new GameObject();
a.transform.right = new Vector3(1, 1, 0);
}
// Use this for initialization
void Start () {
CreateAnEmpty();
}
// Update is called once per frame
void Update () {
}
}
运行以后我们可以发现,虽然CreateAnEmpty函数只在初始化的时候调用了一次,但是创建的空物体并没有随着函数运行完成而自行销毁。如下:
可以发现,场景中就这么多了一个空物体,这其实是我们不希望看到的,那么如何让函数运行结束时自行销毁这个空物体呢?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour {
void CreateAnEmpty()
{
GameObject a = new GameObject();
a.transform.right = new Vector3(1, 1, 0);
Destroy(a);//就是这个
}
// Use this for initialization
void Start () {
CreateAnEmpty();
}
// Update is called once per frame
void Update () {
}
}
只需要在函数运行结束的时候用Destroy函数将物体删除即可。
public static void Destroy(Object obj, float t = 0.0F);
t是用来控制销毁时间的。