Unity 编辑器 leak
2015-04-21 10:28
183 查看
Just for the record.
In Edit mode nothing is executed (obvious, isn’t it?)When entering play mode: Awake(), OnEnable(), Start()
When stopping: OnDisable(), Destroy()
The leak
I want to create a Material inmy code. With knowledge of how MonoBehaviour is living I’ve decided to do it in OnEnable() method and destroy it in OnDisable() method. The reason is simple: I don’t want to reload the scene when I’ll change something that will affect the material code. This
+should be enough:
123456789101112131415 | using UnityEngine; [ExecuteInEditMode]public class Leak : MonoBehaviour { Material material; void OnEnable() { material = new Material(Shader.Find("Diffuse")); } void OnDisable() { DestroyImmediate(material); }} |
Bravo! Here it is!If I think right this will happen every time when Unity will find dynamically created Material that is not attached to any Renderer component. Unity cannot verify if you’ll destroy the object so it fights back with this information above. So there must be a trick to tell Unity that I know what I am doing and I will clean my resources, right?This magic formula is called HideFlags.DontSave. According to documentation “The object will not be saved to the scene. It will not be destroyed when a new scene is loaded“. So this is giving the responsibility for destroying the object back to us. Let’s try it:
1 2 3 4 | voidOnEnable(){ material=newMaterial(Shader.Find("Diffuse")); material.hideFlags=HideFlags.DontSave; } |
Not doing so may break Unity for someone who is using your code.
相关文章推荐
- Unity编辑器拓展之三:拓展Unity的Hierarchy面板
- Unity 3D - 编辑器扩展之修改PackingTag
- unity-编辑器清除控制台日志
- unity之动画编辑器
- [Unity] Unity编辑器中绘制unity自带的小锁
- [Unity编辑器]编辑器与序列化
- (转)初步认识拓展UnityEditor编辑器定制
- [Unity编辑器]与编辑器相关的属性与类
- unity编辑器制作(一)
- lua------------------Unity3D研究院编辑器之打开unity不可识别的文件(十三)
- [Unity编辑器]自定义编辑器界面
- 【Unity优化】怎样实现Unity编辑器中的协程
- Unity编辑器工具错误
- Unity编辑器扩展
- Unity 5.X扩展编辑器之打包assetbundle
- Unity游戏编程定制编辑器(一)
- Unity引擎及编辑器C#源代码赏析(二)—项目组织
- 通过反射调用Unity编辑器提供的各种功能
- Unity应用基础之编辑器与界面
- Unity 在mac好用的代码编辑器--riderRS