This document provides optimization tips for Unity projects. It begins by explaining the problems caused by poor optimization like low frame rates and performance issues. It then provides general optimization tips like optimizing only what is needed and checking optimization results. The rest of the document details optimization techniques for various areas like the engine, code, architecture, physics, sound, UI, textures, meshes, lighting, animation, shaders, terrain and provides useful links for further information.
3. Optimize for... what?
Features of a badly optimized game:
• Low FPS and instability;
• Freezes, errors, crashes;
• High power consumption (mobile projects);
• Long build and recompile (development).
Negative perception of the
game
Lower income
Bad reviews and player retention
4. Optimization problem
Such a distribution of resources, which will ensure their effective use
and the implementation of high-priority tasks first.
Optimal use
of resources
High
performance
Resources
CPU GPU RAM VRAM etc.
6. Optimize what you need
It makes no sense to optimize if:
• there are no performance issues, even in the future;
• there is only an unsubstantiated assumption about the
need to optimize something.
Premature optimization is the root of all evil
D. Knuth
Don't believe assumptions – believe facts.
7. Check your actions
Trust everyone,but always cut the cards
Proverb
• after optimization is done, be sure to check if you have
made it worse;
• if there are several solutions to the problem, it is worth
checking each one if possible – the most unexpected one may
be the best.
8. From the outset plan and develop your project:
• without unnecessary waste of resources;
• with the performance margin;
• considering a variety of bottlenecks;
• considering the featuresof the target platformsand target devices;
• The later the measures are applied, the more difficult they are to apply.
• A game will not cause performance issues on release if it hasn't caused issues
throughout development.
Make optimization a design consideration, not a final step
UnityDocs
Don't put it off till the last moment
9. • There is no universal solution;
• Optimization is a trade-off;
• There is always a slightly more efficient and simpler solution.
Know when to stop
"Will the target user notice it?"
Yes No
10. Everything can be optimized
Eachframe it serializes
the raw Transform-
data and other info
about the object
int id
Vector2Int direction
Vector2 position
id – 1 byte
direction – 4 bits
position – 2 * 4 byte
11. • Don't use MonoBehaviour's OnMouseButton;
• Disable scripts with Update, if they are not visible in the camera;
• Minimize using of Update, LateUpdate and etc;
• sqr-methods are faster then their regularversions;
Engine features
• Using many of the string MonoBehaviour's properties is an allocation (for example tag or name);
• Cache calls of Find, GetComponent, Camera.main and etc.;
• Don't use SendMessage, Invoke and other reflection methods;
12. Engine features
• Use Transform's local data;
• Transform's global data should be cached;
Offset of object
1 000 000 times
Getting Transform
1 000 000 times
• Compare similar methods. Some may be more effective than others;
Null comparison
1 000 000 times
13. • UnityAPI often createsa new copy when returning arrays, which causes allocations;
• Getterscan hide very expensive operations. Cache the results;
• Disablingenabling animators or colliders in idle can be more expensive than always leaving
themon;
• Use MonoBehaviouronly when needed;
• Vector operations are quite expensive. Try touse "scalar math";
Engine features
• When passing a string as a parameter intosome methods, a hash is calculated inside the
methodseach time. It is better to send a pre-cached hash immediately;
// bad way // right way
14. • Unitydoesn't recommend using Resources;
• The more files in Resources - the longer the app takes to load;
Engine features. Resources
• Everything added via inspector on the scene,
even indirectly, willbe loaded along with the scene.
But loading from Resourcesallocates memory
dynamically.
How else to load content:
AssetBundles, Addressable Asset System.
16. • Use Value Type whenever possible;
• Avoid reflection;
• Avoid allocations;
• YieldInstruction can be cached;
• Reuse objects and use shared buffers;
• Use for instead of foreach;
• Avoid anonymous methods and closures;
• Avoid strings and string concatenations;
• Avoid boxing;
• Avoid Linq.
Code optimization tips
closure
Shared buffer. Can be used in
other methods
Boxing: int -> object
concatenation
Anonymous
method
18. Why use it:
• Instantiate and Destroy are expensive
operations;
• the constant creation and destruction of
objects fragment and allocate memory, and
also invoke GC.
Advantages:
• reusing objects;
• no memory fragmentationand no new
allocations;
• no unnecessary GC calls;
• performance.
Disadvantages:
• complication of the code.
Architectural techniques
Object Pooling
20. ECS (Entity Component System)
• Clear separation of
data and logic;
• Flexible and modular
architecture;
• Easy to test;
• Optimal memory usage;
• Performance benefits;
• Possibility of parallel work;
21. ECS (Entity Component System)
• Entity — has no logic and stores only
components.
• Component — stores only data.
• System – processes components.
Implementationsfor Unity:
• Unity DOTS (Preview);
• Entitas;
• LeoECS;
• BrokenBricksECS;
• Svelto.ECS.
22. • Destribute regular logic in scripts across the frames so that it doesn't run in the
same time by all components;
• Use coroutines or async methods instead of Update to execute temporary
logic;
• Update states by events. Don't use checks in Update method for this. Use
Reactive programming, Observer and Event Queue patterns;
• Use appropriate data structuresbased on the operations that will
be performed with these data;
Other techniques
23. Other techniques
• If you have a large number of controlled game objects in space, use a spatial
partition such as QuadTree and other types of trees.
24. • Use different asset packs for different performance devices.
Advantages:
• Resource savings, especially RAM and GPU;
• You can launch projects on low-end devices and provide smooth gameplay.
Disadvantages:
• Reduced asset quality. Especially for textures.
Other techniques
27. • Asset compression;
• Dynamically generated textures, sounds and other assets;
• Store only parts of symmetrical textures;
• Use AssetBundles, that are loaded as they go.
Ways to reduce build size
28. • Don't use physics - many behavioursare easy to simulate;
• Choose the correct Fixed Timestep;
• Work with physics only at physics engine cycle;
• The closer the physical objects are to (0,0,0), the more accurate the
calculations are;
• Don't move staticcolliders (no Rigidbody);
• Use composite simple colliders instead of complex ones;
• Setting Collision matrix;
• Use Raycast less often and limit it to LayerMask and distance;
• Use NonAlloc methods.
Physics optimization tips
29. • If sounds are not game mechanic, you can save on them;
• Don't store sounds you no longer need in memory;
• Controlthe playback of sounds. Avoid playing the same mono-
sounds at the same time;
• Limit the number of simultaneouslysounding effects;
• Use Force To Mono for sounds without stereoeffect;
Sound optimization tips
• Choose appropriate load type:
• Decompress On Load - universal;
• Compressed In Memory - large and frequently used files;
• Streaming - regularlyplayed sounds in a single instance (background music);
• Choose compression type:
• PCM - for short high-definition sounds;
• ADPCM - for short sounds where the presence of noise is not a problem (explosions, bumps, etc.);
• Vorbis - for flexible compression quality settings.
30. • Use texture atlases;
• Use Rect Mask 2D instead of Mask where it is possible;
• Avoid using Layout Group;
• Don't use Graphic Raycaster unnecessarily;
• Disable Raycast Target, Pixel Perfect and Maskable when not required;
• Use different Canvasesfor frequuentlyupdated data: each change triggersa
complete redraw of the whole Canvas;
• Use fewer Canvases: each non-empty Canvasis a new Draw Call.
UI optimization tips
32. POT-texture is texture of size 2N x 2M .
Square and POT textures
When using NPOT-textures, Unity automatically adds
empty spaces as needed to get the desired shapes
and sizes.
33. It is a technique for combining many small isolated textures into one large texture.
Texture atlas Atlas in SpritePacker
Texture atlases
34. Advantages:
• fewer materials and fewer calls to the visualization system when using batch
processing;
• you can turn multiple NPOT-textures into a single POT-texture.
Disadvantages:
• if you use even one texture from the atlas, the entire atlas with other textures
will be loaded into memory;
• if the size of the atlas is larger than the size of the low-level GPU cache, this
causes cache misses and performancedegradation.
Warning note: use atlases with caution in projectswith high-quality textures.
Texture atlases
35. These are pre-prepared sets of textures with different resolutionsfor displaying small distant
objects, that don't require high resolution.
Advantages:
• reduce the cost of rendering texturesthat
don't require high resolution.
Disadvantages:
• increase the file size and loading time.
Definitely not worth using for:
• UI;
• 2D games;
• particles, sprites, meshes, which are displayed
close the camera or at the same distance from
camera.
MipMap
37. Don't use raw PSD and TIFF files. Prepare texture files and export ready-made
ones from editors in advance.
Importing textures
• large size in project;
• hard to use, if you don't have Photoshop;
• Unity doesn't work optimally with such files. As a result,
textures may have a higher size or lower quality.
40. Batch processing is used to group a large number of pieces of data on the CPU
and process them together as a single large block of data on the GPU.
Batch processing
Static
(initialization)
Dynamic
(runtime)
Advantages: you can achieve a significant increase in
renderingefficiency.
42. Disadvantage: a scene, where a large number of objects are dynamically
created, can significantly load the CPU and lose performance, even if the GPU
would be able to process the scene without batching.
Dynamic batch processing
43. Mesh requirements:
• the mesh must have the Staticflag;
• mesh instancesmust use the same material.
Requirementsfor objects:
• objects must not change position;
• objects must be in the scene from the start and can't be created dynamically.
Disadvantages:
• if any mesh in the batch is visible, the entire batch-groupis rendered;
• each copy of the object will be copied to the static batch buffer as a unique set of vertices. It
can be critical if there are identical meshes.
Static batch processing
44. Why:
• optimization of dynamiccreation of a large number of meshes(for example a game world),
when static batching is impossible and dynamic batching is expensive or impossible;
• an alternative to batching, when youneed to manually distribute meshesintogroups;
• increasing convenienceof working with the scene by reducing the number of various objects by
one;
Tools:
• Method Mesh.CombineMeshes;
• MeshCombinerand other ready-made tools in Asset Store;
• 3D computer graphicssoftware;
Combining meshes
45. Copies of materials
Setting materialpropertiesusing
MeshRenderer.material
• Changes the material properties for current
mesh;
• Creates a copy of the material for current
mesh;
• Breaks batching;
MeshRenderer.sharedMaterial
• Changes the material property for all meshes
using it;
• Doesn't create a copy of the material;
• Doesn't break batching;
46. Allows you to draw multiple copies of a single mesh in a single batch, even if
each mesh has different material properties.
Requirements:
• DirectX 11 and DirectX 12 on Windows;
• OpenGL Core 4.1+/ES3.0+ on Windows, macOS,
Linux, iOS and Android;
• Metal on macOS and iOS;
• Vulkan on Windows, Linux and Android;
• PlayStation 4 and Xbox One;
• WebGL (requires WebGL 2.0 API).
GPU (Material) Instancing
51. • Don't use Read/Write unnecessarily (doubles memoryconsumption);
• Optimize Mesh Data can both help with optimization and "kill" your mesh;
• In certain cases, several simple animated meshes can be advantageously combined into one.
Other tips
Disabled Read/Write Enabled Read/Write
52. These functions disable rendering of objects, which are currentlyinvisible for the
camera or they are covered by other objects.
Frustrum and Occlusion Culling
FrustrumCulling Frustrum+ Occlusion Culling
53. • Reduces GPU load;
• Increases CPU load;
• Increases memory consumption, because it makes the scene baking.
Occlusion Culling
54. • Use various baking tools such as LightMap,
LightProbes, ReflectionProbes;
• Use fake shadows for dynamic objects instead of
real ones, when it is possible;
Lighting optimization tips
• Don't use more light sources than necessary.
55. • Reduce the number of objects that are animated at the same time;
• Combine animated objects as needed;
• Reduce the amount of animated parts;
• Animations are calculated on the CPU as standart. You can also animate on the
GPU by animating the vertexes in the shader.
Animation optimization tips
About animation with a shader: https://habr.com/ru/post/507884/
56. • Use mobile versions of shaders for mobile development;
• Always check the standart shaders – they often have bad optimization;
• Use simple data types;
• Avoid conditional statements;
• Reduce the mathematical complexity (don't use expensive pow, exp, log and
etc.);
Shader optimization tips
57. • Remove unnecessary input data;
Shader optimization tips
• Don't use unnecessary shaders in the required list
in Graphics Settings.
• Export only the necessary variables for the inspector;
• Reduce data dependency;
Can be
executed
in parallel
58. • Be careful about the density of objects;
• Reduce the quality of objects, which are not paid enough attention to;
• Reduce the quality of the terrain as you move away from the camera;
• If there are drawdowns on the CPU, it is better to replace a large numer of flat
billboards with volme models (GPU loading);
• It is better to divide a large terrain into pieces and load only visible areas.
Terrain optimization tips
59. Useful links
Books:
• Chris Dickinson. Unity 5 Game Optimization;
• Robert Nystrom. Game Programming Patterns:
http://gameprogrammingpatterns.com
Official guides:
• Unity ECS:
https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/index.html
• Unity Guide to Optimization for Mobiles:
https://docs.unity3d.com/462/Documentation/Manual/MobileOptimizationPracticalGuide.html
• Microsoft Performance recommendations for Unity:
https://docs.microsoft.com/en-us/windows/mixed-reality/develop/unity/performance-recommendations-for-unity
Articles:
• Introduction to ECS: https://medium.com/ingeniouslysimple/entities-components-and-systems-89c31464240d
• Советы по оптимизации Unity проекта: https://syntaxerror.ru/unity-optimizations/
• Анимация с помощью шейдера в Unity: https://dtf.ru/gamedev/152957-animaciya-s-pomoshchyu-sheydera-v-unity
• 10000 Update() calls: https://blogs.unity3d.com/2015/12/23/1k-update-calls/
• Unity Optimization Tips: https://makaka.org/unity-tutorials/optimization#code-scripting
• Unity Android Optimization Guide: https://medium.com/ironequal/android-optimization-with-unity-3504b34f00b0
• Maximizing Your Unity Game's Performance: https://cgcookie.com/articles/maximizing-your-unity-games-performance
60. Useful links
Videos:
• Конвейеры из Factorio в Unity3D: https://youtu.be/L_uwDygZe48
• Оптимизация игр на Unity (MUUG Meetup): https://youtu.be/slmllM5GaYE
• Производительность Unity3D: подводные камни (HighLoad++): https://youtu.be/mAgwkCMuRAk
• Советы по оптимизации кода и памяти (DevGAMM): https://youtu.be/t1u8t5l4ijc
• Своевременная оптимизация проекта (DevGamm): https://youtu.be/ko4XVj8-Hm0
• Оптимизация мобильной графики в Unity (DevGAMM): https://youtu.be/aeLzhlM3piA
• От джуниор/инди разработчика до мидл+ (DevGAMM): https://youtu.be/jqeoq6X-5S8
• Приемы оптимизации памяти в Unity играх (DevGAMM): https://youtu.be/28uLCF-KodA
• Объединение ECS и MonoBehaviour подходо (DevGAMM): https://youtu.be/A9wHFyiRAuE
• Оптимизация сетевого трафика (DevGAMM): https://youtu.be/Kb0WyCB99O0
• Мультиплеер в реальном времени с физикой (DevGAMM): https://youtu.be/EoGkivVH8us
61. Contacts
Link to the slides: https://clck.ru/UMFUt
Email: anton_kerp@mail.ru
VK: vk.com/who_evyork