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

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 in
my 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:

123456789101112131415using UnityEngine; [ExecuteInEditMode]public class Leak : MonoBehaviour { Material material; void OnEnable() { material = new Material(Shader.Find("Diffuse")); } void OnDisable() { DestroyImmediate(material); }}
Do you want to guess what will happen after I put this to game object and hit CTRL + S (Save Scene-)?

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;

}

And that’s it! No more messages about leaking objects! But be careful to always remove your objects by DestroyImmediate().
Not doing so may break Unity for someone who is using your code.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: