天天看点

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

自Unity 2019.2起,Unity添加了可以处理这种情况的新API ——TryGetComponent API。与GetComponent相比,一个最大的区别是,当请求的Component不存在时,此方法不会在编辑器中分配内存。

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

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

需要注意的是,这个内存分配只会发生在Editor中。更多相关内容可以查看这篇文章:

https://zhuanlan.zhihu.com/p/26763624

但是这里的内存分配是如何产生的呢?

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

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测试的结果。

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

Useful Link:

https://connect.unity.com

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

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

本作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可,我的博客欢迎复制共享,但在同时,希望保留我的署名权陈嘉栋(慕容小匹夫),并且,不得用于商业用途。如您有任何疑问或者授权方面的协商,请给我留言。

知乎专栏:

Runtime

联系方式:

Email:[email protected]