Skip to content

Unity coding tips

The following tips will help you write better code so your game runs smoother in the browser.

Memory optimization

Unity uses a memory heap to store the objects, scenes, shaders, etc. when your game is running in the browser. The memory heap is resized automatically by Unity when needed. However, errors may happen during the resizing process, since the browser may fail to allocate more memory for resizing the heap. That's why it's important to keep your memory usage as low as possible. This also benefits the game when running on weaker devices, like mobile devices. You can find more information about memory usage on the official Unity documentation.

Garbage collection

The garbage collector runs at the end of every frame in WebGL, so there are various minor optimizations you can do to your code to generate less garbage.

  • avoid doing string concatenation in loops, since this may generate a lot of garbage during a single frame and Unity may run out of memory
  • for string concatenations, if the number of concatenated elements exceeds 10, it is recommended to start using StringBuilder
  • cache arrays returned by the functions before using them in a for loop. In other words, avoid for(int i=0;i<getArray();i++)
  • use gameObject.CompareTag("tagName") for tag comparison, since it doesn't allocate memory for the tag and is much more performant
  • for coroutines, cache the yield, for example, var delay = new WaitForSeconds(5.0f); if you need to return it multiple times

Asset bundles

The asset bundles are loaded directly into the heap and the browser doesn't need to allocate memory for them. Another benefit of asset bundles is the decreased loading time for your game since the unity data files will be smaller.

You can find more tips to decrease code memory usage on the official Unity documentation.