Unity 3D Code optimization tips

I’ve been holding off on attempting to write more optimized code in Unity 3D until I have a basic grasp on putting a project together, but I’ve had a nagging suspicion that there’s plenty of poorly optimized code floating around in the examples I’ve learned from.

Fortunately, many of the lessons learned from optimizing ActionScript 3 apply just as well to Unity. If you’re a regular reader here you’ve likely heard me harp on similar topics in the Flash world. Here are some of the most important things I’ve uncovered over the course of the day:

  • You should cache references to components whenever possible. Never call GameObject.Find() or gameObject.GetComponent() inside of an Update() method. These are very slow methods that get slower as the number of objects in your scene grows. Grab all the references you need in Start(), or add to them dynamically as you need them. This is one of the most frequently abused and broken rules in the Unity demo code, and stripping it out gave me an extra precious 5fps on my Android device.
  • The native OnGUI method may be a very convenient way to lay out a gui, but during gameplay should be avoided like the plague. It’s fine for static title screens, or scenes with little action, but even an empty OnGUI call is a nightmare for your framerate. For a detailed overview, check this link.
  • Provoking a garbage collection cycle is a kiss of death for your framerate. Try never to instantiate inside of an Update() method. Create as much as you can upfront and recycle what is practical. Object pools, and cached instances once again come to the rescue here.

  1. No comments yet.