Unity3D脚本中创建的gameobject如何删除
2017-10-06 09:26
239 查看
我本来以为unity里的Gameobject类就是一个正常的类,生命周期和正常的类一样,结果发现不是的。
unity里如果你在脚本里的某个函数里定义一个Gameobject,它不会作为一个局部变量随着函数的终止而自动销毁。如下:
运行以后我们可以发现,虽然CreateAnEmpty函数只在初始化的时候调用了一次,但是创建的空物体并没有随着函数运行完成而自行销毁。如下:
可以发现,场景中就这么多了一个空物体,这其实是我们不希望看到的,那么如何让函数运行结束时自行销毁这个空物体呢?
只需要在函数运行结束的时候用Destroy函数将物体删除即可。
public static void Destroy(Object obj, float t = 0.0F);
t是用来控制销毁时间的。
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是用来控制销毁时间的。
相关文章推荐
- windbg脚本实践2----监控特定注册表键值创建和删除
- 如何在Unity3d中创建激光束
- 通过一个备份归档的脚本演示rsync限速和find如何删除文件
- SQL升级脚本先删除后创建,可保证每次都可以正常运行!
- BASIS-如何删除SAP在用户修改表结构时创建的临时表
- 如何获得创建控制文件的脚本并重建控制文件
- Shell脚本控制tomcat的docker容器的创建,删除,启动,关闭
- Unity3D之如何创建正确的像素比在屏幕上
- 如何在C#中用程序执行指定的SQL脚本文件,实现自动安装创建数据库
- 动态创建对象,并渲染贴图,动态添加删除脚本
- 如何使用脚本在derby数据库中创建表
- Unity3d XML的创建、更新、添加、删除和读取
- [脚本] Unity3d 如何用GL画线
- shell脚本操作mysql数据库,使用mysql的-e参数可以执行各种sql的(创建,删除,增,删,改、查)等各种操作
- 如何彻底删除Oracle数据库,以创建相同实例名称的库
- unity3D导出exe文件,总是有个设置窗口,来设置分辨率和其他参数。如何删除掉这一步?
- 创建二叉树 二叉树如何删除节点操作教程
- 使用PD(PowerDesigner)图如何快速生成创建数据库表的SQL脚本
- django 删除table后如何重新创建
- 如何使用脚本批量创建虚拟机(上)