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:
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:
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.
本文介绍如何在Unity中创建并管理动态材质,通过使用OnEnable()和OnDisable()方法结合HideFlags.DontSave标志来避免资源泄露的问题。
2900

被折叠的 条评论
为什么被折叠?



