问题现象
从 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.