Basics of Optimization in Unity

The importance of caching GetComponent:

GetComponent does exactly what it says, it commits Unity to perform an action requiring searching and allocating memory. If this is being done in Update, that search and allocation are being done 60 times a second! As in yesterday's example, if you create a variable to hold that GetComponent, it will already be available for Unity to use and save a significant amount of time!

New isn’t always better!

One must be careful when using the new keyword as it usually creates a class that gets placed on the heap and becomes a candidate for garbage collection, unlike structs that get placed on a stack and are not garbage collected. Structs are actually a lightweight version of classes and you can learn more about them here.

Precise PinPointing Pesky Performance Problems with Profiler!

You can create special profiler labels in your code so you can see the direct impact of that code segment! Remember you’ll have to use UnityEngine.Profiler namespace!

Use Visual Studio to check if something is a class or struct

Pressing F12 will tell you if a command is a class or a struct. If it’s a class, you’ll know if you’ll need to cache it.

Cache those yield returns!

When testing between a regular return and one with a cached WaitForSecond() method, the regular one used 3x more bytes than the cached! It’s always a good idea to cache your WaitForSeconds()!

Better RayCasting methods are available

Unity has optimized Raycasting and you can find them with the words NonAlloc. Ex: RaycastNonAlloc or SphereCastNonAlloc. Use them.

Camera.Main is a hog!

cache Camera.Main to save more memory.

Lists vs Arrays

Try to go with lists. They’re leaner and less memory intensive. Arrays must constantly be recreated from scratch when modified which could take up valuable processing power from other functions.

Structs vs Classes

Try to go with Structs as much as you can. They don’t get thrown on the heap and are extremely fast. A general rule of thumb is if a class has 5 or less variables and doesn’t need inheritance, go with the struct.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Esteban Ibarra

Esteban Ibarra

cartoonist, game artist, and wanabe gamedev.