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

我本来以为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是用来控制销毁时间的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值