Use TryGetComponent substituted GetComponent to avoid memory allocation in Editor

Unity as a developer, you may come across a more or less common GC allocation of Unity - will allocate additional memory when Component to get a non-existent method in use GetComponent Editor. Like the figure below

It should be noted that this memory allocation only occurs in the Editor. More details can check out this article:

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

 

But here is how to allocate memory to generate it?

This is because when MonoBehaviour have fields in the Unity Editor does not set these fields as a true "null", but is set to indicate "null" pseudo empty object. If the requested Component does not exist, Unity generates a custom alert strings in the newly assigned pseudo empty object. For information, you can view this blog.

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

But the good news is that starting from Unity 2019.2, Unity added a new API --TryGetComponent API can handle such a situation.

https://unity.cn/releases/full/2019/2019.2.0

Compared with GameObject.GetComponent, a big difference is that, when Component requested does not exist, this method does not allocate memory in the editor. The screenshot below is the result of the use of TryGetComponent tests.

 

 

Useful Link:

https://connect.unity.com

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

 

 

Guess you like

Origin www.cnblogs.com/murongxiaopifu/p/11697201.html