SlideShare une entreprise Scribd logo
1  sur  62
Télécharger pour lire hors ligne
simple tips for developing with "no surprises"
Kerp Anton
Unity Developer
Optimization in Unity:
Content
• Optimization problem;
• General optimization tips;
• Engine features;
• Code optimization tips;
• Architectural techniques;
• Physics optimization tips;
• Sound optimizations tips;
• UI oprimization tips;
• Texture optimization tips;
• Mesh optimization tips;
• Lighting optimization tips;
• Animation optimization tips;
• Shader optimization tips;
• Terrain optimization tips;
• Useful links.
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
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.
OPTIMIZATION
Don't go to extremes
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.
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.
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
• 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
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
• 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;
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
• 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
• 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.
Engine features. Resources
Inspector
Resources
Use
1st texture
Use
2nd texture
Stop
using
Have: 100 different textures 2048х2048.
Build: Windows 10 x86
• 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
Inheritance is dangerous
Screenshot fromthe article: https://syntaxerror.ru/unity-optimizations/
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
Architectural techniques
Object Pooling
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;
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.
• 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
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.
• 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
The original asset pack
The asset pack for low-end devices
• 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
• 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
• 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.
• 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
Larger texture
file size
More GPU
memory
bandwidth
Texture optimization tips
Compression
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.
It is a technique for combining many small isolated textures into one large texture.
Texture atlas Atlas in SpritePacker
Texture atlases
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
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
Disabled MipMap Enabled MipMap
MipMap
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.
Check settings
Mesh optimization tips
Less polygons
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.
Main requirement:
Note: SkinnedMeshRenderer neverparticipatesin batch processing.
Batch processing
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
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
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
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;
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
GPU Instancing for custom shader
Advantages:
• Performance.
Disadvantages:
• Inconvenient.
How to use:
• Graphics.DrawMesh.
What to watch:
• https://youtu.be/L_uwDygZe48
Drawing meshes without GameObject
Level of Detail (LOD)
Transparent geometry
Opaque
gems
Transparent
gems
• 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
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
• Reduces GPU load;
• Increases CPU load;
• Increases memory consumption, because it makes the scene baking.
Occlusion Culling
• 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.
• 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/
• 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
• 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
• 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
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
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
Contacts
Link to the slides: https://clck.ru/UMFUt
Email: anton_kerp@mail.ru
VK: vk.com/who_evyork
Optimization in Unity: simple tips for developing with "no surprises" / Anton Kerp (Frostgate)

Contenu connexe

Tendances

Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
Johan Andersson
 
The Technology of Uncharted: Drake’s Fortune
The Technology of Uncharted: Drake’s FortuneThe Technology of Uncharted: Drake’s Fortune
The Technology of Uncharted: Drake’s Fortune
Naughty Dog
 
Moving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based RenderingMoving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based Rendering
Electronic Arts / DICE
 
Z Buffer Optimizations
Z Buffer OptimizationsZ Buffer Optimizations
Z Buffer Optimizations
pjcozzi
 

Tendances (20)

Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019
 
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016
 
Masked Occlusion Culling
Masked Occlusion CullingMasked Occlusion Culling
Masked Occlusion Culling
 
The Technology of Uncharted: Drake’s Fortune
The Technology of Uncharted: Drake’s FortuneThe Technology of Uncharted: Drake’s Fortune
The Technology of Uncharted: Drake’s Fortune
 
DirectX 11 Rendering in Battlefield 3
DirectX 11 Rendering in Battlefield 3DirectX 11 Rendering in Battlefield 3
DirectX 11 Rendering in Battlefield 3
 
Mobile Performance Tuning: Poor Man's Tips And Tricks
Mobile Performance Tuning: Poor Man's Tips And TricksMobile Performance Tuning: Poor Man's Tips And Tricks
Mobile Performance Tuning: Poor Man's Tips And Tricks
 
Terrain in Battlefield 3: A Modern, Complete and Scalable System
Terrain in Battlefield 3: A Modern, Complete and Scalable SystemTerrain in Battlefield 3: A Modern, Complete and Scalable System
Terrain in Battlefield 3: A Modern, Complete and Scalable System
 
Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)
Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)
Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)
 
Triangle Visibility buffer
Triangle Visibility bufferTriangle Visibility buffer
Triangle Visibility buffer
 
[Kgc2012] deferred forward 이창희
[Kgc2012] deferred forward 이창희[Kgc2012] deferred forward 이창희
[Kgc2012] deferred forward 이창희
 
Design your 3d game engine
Design your 3d game engineDesign your 3d game engine
Design your 3d game engine
 
Frostbite on Mobile
Frostbite on MobileFrostbite on Mobile
Frostbite on Mobile
 
Stylized Rendering in Battlefield Heroes
Stylized Rendering in Battlefield HeroesStylized Rendering in Battlefield Heroes
Stylized Rendering in Battlefield Heroes
 
Moving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based RenderingMoving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based Rendering
 
Built for performance: the UIElements Renderer – Unite Copenhagen 2019
Built for performance: the UIElements Renderer – Unite Copenhagen 2019Built for performance: the UIElements Renderer – Unite Copenhagen 2019
Built for performance: the UIElements Renderer – Unite Copenhagen 2019
 
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
 
Z Buffer Optimizations
Z Buffer OptimizationsZ Buffer Optimizations
Z Buffer Optimizations
 
Rendering Technologies from Crysis 3 (GDC 2013)
Rendering Technologies from Crysis 3 (GDC 2013)Rendering Technologies from Crysis 3 (GDC 2013)
Rendering Technologies from Crysis 3 (GDC 2013)
 
Photogrammetry and Star Wars Battlefront
Photogrammetry and Star Wars BattlefrontPhotogrammetry and Star Wars Battlefront
Photogrammetry and Star Wars Battlefront
 

Similaire à Optimization in Unity: simple tips for developing with "no surprises" / Anton Kerp (Frostgate)

Дмитрий Вовк - Learn iOS Game Optimization. Ultimate Guide
Дмитрий Вовк - Learn iOS Game Optimization. Ultimate GuideДмитрий Вовк - Learn iOS Game Optimization. Ultimate Guide
Дмитрий Вовк - Learn iOS Game Optimization. Ultimate Guide
UA Mobile
 
Smedberg niklas bringing_aaa_graphics
Smedberg niklas bringing_aaa_graphicsSmedberg niklas bringing_aaa_graphics
Smedberg niklas bringing_aaa_graphics
changehee lee
 

Similaire à Optimization in Unity: simple tips for developing with "no surprises" / Anton Kerp (Frostgate) (20)

Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...
Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...
Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...
 
0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri
 
Optimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark HarknessOptimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark Harkness
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
 
Profiling tools and Android Performance patterns
Profiling tools and Android Performance patternsProfiling tools and Android Performance patterns
Profiling tools and Android Performance patterns
 
Дмитрий Вовк - Learn iOS Game Optimization. Ultimate Guide
Дмитрий Вовк - Learn iOS Game Optimization. Ultimate GuideДмитрий Вовк - Learn iOS Game Optimization. Ultimate Guide
Дмитрий Вовк - Learn iOS Game Optimization. Ultimate Guide
 
Optimizing Games for Mobiles
Optimizing Games for MobilesOptimizing Games for Mobiles
Optimizing Games for Mobiles
 
"Making Computer Vision Software Run Fast on Your Embedded Platform," a Prese...
"Making Computer Vision Software Run Fast on Your Embedded Platform," a Prese..."Making Computer Vision Software Run Fast on Your Embedded Platform," a Prese...
"Making Computer Vision Software Run Fast on Your Embedded Platform," a Prese...
 
Smedberg niklas bringing_aaa_graphics
Smedberg niklas bringing_aaa_graphicsSmedberg niklas bringing_aaa_graphics
Smedberg niklas bringing_aaa_graphics
 
Android performance
Android performanceAndroid performance
Android performance
 
[TGDF 2020] Mobile Graphics Best Practices for Artist
[TGDF 2020] Mobile Graphics Best Practices for Artist[TGDF 2020] Mobile Graphics Best Practices for Artist
[TGDF 2020] Mobile Graphics Best Practices for Artist
 
【Unite Tokyo 2018】実践的なパフォーマンス分析と最適化
【Unite Tokyo 2018】実践的なパフォーマンス分析と最適化【Unite Tokyo 2018】実践的なパフォーマンス分析と最適化
【Unite Tokyo 2018】実践的なパフォーマンス分析と最適化
 
[Unity Forum 2019] Mobile Graphics Optimization Guides
[Unity Forum 2019] Mobile Graphics Optimization Guides[Unity Forum 2019] Mobile Graphics Optimization Guides
[Unity Forum 2019] Mobile Graphics Optimization Guides
 
Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)
 
4 memory management bb
4   memory management bb4   memory management bb
4 memory management bb
 
iOS App performance - Things to take care
iOS App performance - Things to take careiOS App performance - Things to take care
iOS App performance - Things to take care
 
Approximation techniques used for general purpose algorithms
Approximation techniques used for general purpose algorithmsApproximation techniques used for general purpose algorithms
Approximation techniques used for general purpose algorithms
 
[Unite Seoul 2020] Mobile Graphics Best Practices for Artists
[Unite Seoul 2020] Mobile Graphics Best Practices for Artists[Unite Seoul 2020] Mobile Graphics Best Practices for Artists
[Unite Seoul 2020] Mobile Graphics Best Practices for Artists
 
Developing Next-Generation Games with Stage3D (Molehill)
Developing Next-Generation Games with Stage3D (Molehill) Developing Next-Generation Games with Stage3D (Molehill)
Developing Next-Generation Games with Stage3D (Molehill)
 

Plus de DevGAMM Conference

Plus de DevGAMM Conference (20)

The art of small steps, or how to make sound for games in conditions of war /...
The art of small steps, or how to make sound for games in conditions of war /...The art of small steps, or how to make sound for games in conditions of war /...
The art of small steps, or how to make sound for games in conditions of war /...
 
Breaking up with FMOD - Why we ended things and embraced Metasounds / Daniel ...
Breaking up with FMOD - Why we ended things and embraced Metasounds / Daniel ...Breaking up with FMOD - Why we ended things and embraced Metasounds / Daniel ...
Breaking up with FMOD - Why we ended things and embraced Metasounds / Daniel ...
 
How Audio Objects Improve Spatial Accuracy / Mads Maretty Sønderup (Audiokine...
How Audio Objects Improve Spatial Accuracy / Mads Maretty Sønderup (Audiokine...How Audio Objects Improve Spatial Accuracy / Mads Maretty Sønderup (Audiokine...
How Audio Objects Improve Spatial Accuracy / Mads Maretty Sønderup (Audiokine...
 
Why indie developers should consider hyper-casual right now / Igor Gurenyov (...
Why indie developers should consider hyper-casual right now / Igor Gurenyov (...Why indie developers should consider hyper-casual right now / Igor Gurenyov (...
Why indie developers should consider hyper-casual right now / Igor Gurenyov (...
 
AI / ML for Indies / Tyler Coleman (Retora Games)
AI / ML for Indies / Tyler Coleman (Retora Games)AI / ML for Indies / Tyler Coleman (Retora Games)
AI / ML for Indies / Tyler Coleman (Retora Games)
 
Agility is the Key: Power Up Your GameDev Project Management with Agile Pract...
Agility is the Key: Power Up Your GameDev Project Management with Agile Pract...Agility is the Key: Power Up Your GameDev Project Management with Agile Pract...
Agility is the Key: Power Up Your GameDev Project Management with Agile Pract...
 
New PR Tech and AI Tools for 2023: A Game Changer for Outreach / Kirill Perev...
New PR Tech and AI Tools for 2023: A Game Changer for Outreach / Kirill Perev...New PR Tech and AI Tools for 2023: A Game Changer for Outreach / Kirill Perev...
New PR Tech and AI Tools for 2023: A Game Changer for Outreach / Kirill Perev...
 
Playable Ads - Revolutionizing mobile games advertising / Jakub Kukuryk (Popc...
Playable Ads - Revolutionizing mobile games advertising / Jakub Kukuryk (Popc...Playable Ads - Revolutionizing mobile games advertising / Jakub Kukuryk (Popc...
Playable Ads - Revolutionizing mobile games advertising / Jakub Kukuryk (Popc...
 
Creative Collaboration: Managing an Art Team / Nastassia Radzivonava (Glera G...
Creative Collaboration: Managing an Art Team / Nastassia Radzivonava (Glera G...Creative Collaboration: Managing an Art Team / Nastassia Radzivonava (Glera G...
Creative Collaboration: Managing an Art Team / Nastassia Radzivonava (Glera G...
 
From Local to Global: Unleashing the Power of Payments / Jan Kuhlmannn (Xsolla)
From Local to Global: Unleashing the Power of Payments / Jan Kuhlmannn (Xsolla)From Local to Global: Unleashing the Power of Payments / Jan Kuhlmannn (Xsolla)
From Local to Global: Unleashing the Power of Payments / Jan Kuhlmannn (Xsolla)
 
Strategies and case studies to grow LTV in 2023 / Julia Iljuk (Balancy)
Strategies and case studies to grow LTV in 2023 / Julia Iljuk (Balancy)Strategies and case studies to grow LTV in 2023 / Julia Iljuk (Balancy)
Strategies and case studies to grow LTV in 2023 / Julia Iljuk (Balancy)
 
Why is ASO not working in 2023 and how to change it? / Olena Vedmedenko (Keya...
Why is ASO not working in 2023 and how to change it? / Olena Vedmedenko (Keya...Why is ASO not working in 2023 and how to change it? / Olena Vedmedenko (Keya...
Why is ASO not working in 2023 and how to change it? / Olena Vedmedenko (Keya...
 
How to increase wishlists & game sales from China? Growth marketing tactics &...
How to increase wishlists & game sales from China? Growth marketing tactics &...How to increase wishlists & game sales from China? Growth marketing tactics &...
How to increase wishlists & game sales from China? Growth marketing tactics &...
 
Turkish Gaming Industry and HR Insights / Mustafa Mert EFE (Zindhu)
Turkish Gaming Industry and HR Insights / Mustafa Mert EFE (Zindhu)Turkish Gaming Industry and HR Insights / Mustafa Mert EFE (Zindhu)
Turkish Gaming Industry and HR Insights / Mustafa Mert EFE (Zindhu)
 
Building an Awesome Creative Team from Scratch, Capable of Scaling Up / Sasha...
Building an Awesome Creative Team from Scratch, Capable of Scaling Up / Sasha...Building an Awesome Creative Team from Scratch, Capable of Scaling Up / Sasha...
Building an Awesome Creative Team from Scratch, Capable of Scaling Up / Sasha...
 
Seven Reasons Why Your LiveOps Is Not Performing / Alexander Devyaterikov (Be...
Seven Reasons Why Your LiveOps Is Not Performing / Alexander Devyaterikov (Be...Seven Reasons Why Your LiveOps Is Not Performing / Alexander Devyaterikov (Be...
Seven Reasons Why Your LiveOps Is Not Performing / Alexander Devyaterikov (Be...
 
The Power of Game and Music Collaborations: Reaching and Engaging the Masses ...
The Power of Game and Music Collaborations: Reaching and Engaging the Masses ...The Power of Game and Music Collaborations: Reaching and Engaging the Masses ...
The Power of Game and Music Collaborations: Reaching and Engaging the Masses ...
 
Branded Content: How to overcome players' immunity to advertising / Alex Brod...
Branded Content: How to overcome players' immunity to advertising / Alex Brod...Branded Content: How to overcome players' immunity to advertising / Alex Brod...
Branded Content: How to overcome players' immunity to advertising / Alex Brod...
 
Resurrecting Chasm: The Rift - A Source-less Remastering Journey / Gennadii P...
Resurrecting Chasm: The Rift - A Source-less Remastering Journey / Gennadii P...Resurrecting Chasm: The Rift - A Source-less Remastering Journey / Gennadii P...
Resurrecting Chasm: The Rift - A Source-less Remastering Journey / Gennadii P...
 
How NOT to do showcase events: Behind the scenes of Midnight Show / Andrew Ko...
How NOT to do showcase events: Behind the scenes of Midnight Show / Andrew Ko...How NOT to do showcase events: Behind the scenes of Midnight Show / Andrew Ko...
How NOT to do showcase events: Behind the scenes of Midnight Show / Andrew Ko...
 

Dernier

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 

Optimization in Unity: simple tips for developing with "no surprises" / Anton Kerp (Frostgate)

  • 1. simple tips for developing with "no surprises" Kerp Anton Unity Developer Optimization in Unity:
  • 2. Content • Optimization problem; • General optimization tips; • Engine features; • Code optimization tips; • Architectural techniques; • Physics optimization tips; • Sound optimizations tips; • UI oprimization tips; • Texture optimization tips; • Mesh optimization tips; • Lighting optimization tips; • Animation optimization tips; • Shader optimization tips; • Terrain optimization tips; • Useful links.
  • 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.
  • 15. Engine features. Resources Inspector Resources Use 1st texture Use 2nd texture Stop using Have: 100 different textures 2048х2048. Build: Windows 10 x86
  • 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
  • 17. Inheritance is dangerous Screenshot fromthe article: https://syntaxerror.ru/unity-optimizations/
  • 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
  • 26. The asset pack for low-end devices
  • 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
  • 31. Larger texture file size More GPU memory bandwidth Texture optimization tips Compression
  • 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
  • 36. Disabled MipMap Enabled MipMap 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.
  • 41. Main requirement: Note: SkinnedMeshRenderer neverparticipatesin batch processing. Batch processing
  • 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
  • 47. GPU Instancing for custom shader
  • 48. Advantages: • Performance. Disadvantages: • Inconvenient. How to use: • Graphics.DrawMesh. What to watch: • https://youtu.be/L_uwDygZe48 Drawing meshes without GameObject
  • 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