UnityBug——Poolable Component 失效问题

问题现象


从 Pool 中取出的 GameObject,通过 GetOrAddComponent 获取其上的 Component 可能失效

问题分析


Destroy 的 Component 不会立即销毁,会在当前 Update 之后 Rendering 之前真正销毁
在 GameObject 被 Push 进 Pool 时,Destroy 了其 Component
正好在当前 Update 该 GameObject 立即被取出来,在尝试 GetComponent 时取出了该被销毁但还未销毁的 Component
这个 Component 在之后被 Unity 销毁后,就会失效

解决方案


Unity 并没有提供方法合适的判断一个 Component 是否要被销毁
如果是自己维护的话,不要使用 GetOrAddComponent,直接 AddComponent
简单处理的话,使用 DestroyImmediate 立即销毁,但是这样会影响主线程


参考文档

The object obj will be destroyed now or if a time is specified t seconds from now. If obj is a Component it will remove the component from the GameObject and destroy it. If obj is a GameObject it will destroy the GameObject, all its components and all transform children of the GameObject. Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值