Should I cache things like the main camera and the current transform?

There’s no general rule. If I’m hammering out a piece of code for a quick gamejam or just to satisfy my own curiosity about a game feature, the answer is gonna be different than if I am making a whole new subsystem for a game.

As long as you understand what stuff does, you can reason about the code you are doing.

For instance, with Camera.main (and just about anything else), you can see what it does here:

There is even a discussion about performance.

Vector3 is a value type, NOT a reference, so be sure you understand that fundamental difference. Vector3.zero is just a handy shortcut for making zero vectors. You can get the same thing with new Vector3();

Finally, always keep this in mind: DO NOT OPTIMIZE CODE JUST BECAUSE… If you don’t have a problem, DO NOT OPTIMIZE!

If you DO have a problem, always start by using the profiler:

Window → Analysis → Profiler

Failure to use the profiler means you’re just guessing, making a mess of your code for no good reason.

Notes on optimizing UnityEngine.UI setups:

1 Like