Unity 编辑器 leak

来源:互联网 发布:淘宝装修软件哪个好 编辑:程序博客网 时间:2024/05/22 03:40

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-)?

leaking

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.

0 0
原创粉丝点击