Unity optimization: My code

Unity optimization is Hard. There are many things to get right. Here’s a list for myself of things to check in my own code. Mostly from “Optimize your game
performance for consoles and PCs in Unity” from Unity itself.

These are things to consider, not tings that must be done, init bruv.

  • Use StringBuilder to reduce GC calls
  • Avoid parsing JSON and XML. Consider ScriptableObjects
  • Don’t make new arrays and tings inside loops, bruv. Cache refs to them.
  • Some Unity API methods do heap allocations. Use those that don’t like GameObject.CompareTag. Esp in loops.
  • Avoid passing a value-typed variable in place of a reference-typed variable. This creates a temporary object. I didn’t know this. Make concrete overrides, or use generics.
  • Coroutines. Cache and reuse the WaitForSeconds object rather than creating it in the yield line. Huh.
  • Have small Update(), LateUpdate(), etc. Don’t declare lists and such in every frame.
  • Run code every n frames. From da book:
private int interval = 3;
void Update()
{
  if (Time.frameCount % interval == 0)
  {
    ExampleExpensiveFunction();
  }
}

  • Cache component and GameObject references in Awake().
  • Avoid expensive logic in Awake and Start until your application renders its first frame. Can have a coroutine with WaitForEndOfFrame, or awaitable, or some such.
  • Remove log statements. I use debug flags on GOs. Should be OK, if I remember to turn them off.
  • For get/set with animator, use integer-valued methods, not stringy ones.
  • Don’t add components at runtime. Use prefabs.
  • Object pooling. Unity includes a built-in object pooling feature via the UnityEngine.Pool namespace. I didn’t know!
  • When messing with Transforms, use Transform.SetPositionAndRotation to update both position and rotation at once.
  • When instantiating prefabs at run time, use the method that takes a lotta params.
  • Store unchanging stuff in a scriptable object.
  • Avoid lambda expressions. They do allocations.

Leave a Comment

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

Auto
Scroll to Top