Unity 编辑器 leak

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值