您的位置:首页 > 移动开发 > Unity3D

Unity3D脚本中创建的gameobject如何删除

2017-10-06 09:26 239 查看
我本来以为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是用来控制销毁时间的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: