Using Trygetcomponent Instead of Getcomponent to Avoid Memory Allocation in the Editor
This post was first published at Medium
If you are a Unity developer, you may find that memory allocation in the editor when you call GetComponent() to query for a component that doesn’t exist. Just like the screenshot below.
It should be noted that this memory allocation will only occur in the Editor. But why is this memory allocation happening? This is because when a MonoBehaviour has fields, Unity dose not set those fields to “real null”, but to a “fake null” object. If the requested component does not exist, Unity will generate a custom warning string inside the newly allocated fake null object. For more information, you can check this blog out.
However, since Unity 2019.2 Unity has added a new API that can handle this situation, the TryGetComponent API. The notable difference compared to GameObject.GetComponent is that this method does not allocate in the editor when the requested component does not exist. The screenshot below is the result of testing with TryGetComponent.