Get the Right Component!

I’ve been using Unity for a while, but I’ve only been coding (for realz) for about a year. I’m currently refactoring some of the code I wrote a year ago, and seeing lots of things I can do better.

One thing I’m seeing way too much of is this:

I’m assigning a GameObject in the inspector, and then getting the Image component in Start().

What’s wrong with this?

In many cases I don’t need the GameObject beyond the Start() method, so having it hanging around is pretty much pointless, and getting all those components at the start (or any other time) causes an unnecessary delay.

A much better way to do it is to make sure to get the component you need the first time:

Using this code I can still drag the game object to the field in the inspector. It just references the Image component instead of the GameObject. Doing things this way isn’t just faster, the code and the inspector are much more readable which makes things much easier.


From there if I need the game object I can use Component.gameObject:

It’s much quicker to get the game object from a component than it is to get a component from a game object, because Unity doesn’t have to find anything. Getting the transform is easy too, but just be aware that .transform is still .GetComponent<Transform>() under the hood – so it might be saving your keyboard, but not your frame rate.

Also (when I’m not being lazy), I’ve been trying to make sure that my access modifiers are appropriate. Adding [SerializeField] instead of public when I need to access a field in the inspector is much better. It really is a good practice to get into, especially as your code gets bigger and more complex.

Get the Right Component!

Leave a Reply

Your email address will not be published. Required fields are marked *