使用TryGetComponent取代GetComponent以免Editor中的内存分配

做为Unity开发人员,可能或多或少都会遇到过一个常见的Unity的GC分配问题——在Editor中使用GetComponent方法来获取一个不存在的Component时会分配额外的内存。就像下图编辑器

须要注意的是,这个内存分配只会发生在Editor中。更多相关内容能够查看这篇文章:测试

https://zhuanlan.zhihu.com/p/267636243d

 

可是这里的内存分配是如何产生的呢?对象

这是由于当MonoBehaviour具备字段时,在Editor中Unity不会将这些字段设置为真正的“null”,而是设置为表示“null”的伪空对象。若是所请求的Component不存在,则Unity将在新分配的伪空对象内生成一个自定义警告字符串。有关信息,你们能够查看此博客。blog

https://blogs.unity3d.com/2014/05/16/custom-operator-should-we-keep-it/内存

不过好消息是,自Unity 2019.2起,Unity添加了能够处理这种状况的新API ——TryGetComponent API。开发

https://unity.cn/releases/full/2019/2019.2.0字符串

与GameObject.GetComponent相比,一个最大的区别是,当请求的Component不存在时,此方法不会在编辑器中分配内存。下面的屏幕截图是使用TryGetComponent测试的结果。get

 

 

Useful Link:

https://connect.unity.com博客

https://docs.microsoft.com/zh-cn/learn/?WT.mc_id=DT-MVP-5001664

相关文章
相关标签/搜索