Unity Tip: Use TryGetComponent instead of GetComponent to avoid memory allocation in the Editor

Jiadong Chen
Oct 13 · 2 min read

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.

chenjd.xyz

Record work and life. Focus on software development, Unity and C#.

Jiadong Chen

Written by

Programmer | Author | Blogger | Speaker | Microsoft Developer Technologies MVP | @Unity3d China | Views = my own

chenjd.xyz

Record work and life. Focus on software development, Unity and C#.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade