Unity Game Optimization - Third Edition

Book description

Get up to speed with a series of performance-enhancing coding techniques and methods that will help you improve the performance of your Unity applications

Key Features

  • Optimize graphically intensive games using the latest features of Unity such as Electronic Clearance Service (ECS) and the Burst compiler
  • Explore techniques for solving performance issues with your VR projects
  • Learn best practices for project organization to save time through an improved workflow

Book Description

Unity engine comes with a great set of features to help you build high-performance games. This Unity book is your guide to optimizing various aspects of your game development, from game characters and scripts, right through to animations.

You'll explore techniques for writing better game scripts and learn how to optimize a game using Unity technologies such as ECS and the Burst compiler. The book will also help you manage third-party tooling used with the Unity ecosystem. You'll also focus on the problems in the performance of large games and virtual reality (VR) projects in Unity, gaining insights into detecting performance issues and performing root cause analysis. As you progress, you'll discover best practices for your Unity C# script code and get to grips with usage patterns. Later, you'll be able to optimize audio resources and texture files, along with effectively storing and using resource files. You'll then delve into the Rendering Pipeline and learn how to identify performance problems in the pipeline. In addition to this, you'll learn how to optimize the memory and processing unit of Unity. Finally, you'll cover tips and tricks used by Unity professionals to improve the project workflow.

By the end of this book, you'll have developed the skills you need to build interactive games using Unity and its components.

What you will learn

  • Apply the Unity Profiler to find bottlenecks in your app, and discover how to resolve them
  • Discover performance problems that are critical for VR projects and learn how to tackle them
  • Enhance shaders in an accessible way, optimizing them with subtle yet effective performance tweaks
  • Use the physics engine to keep scenes as dynamic as possible
  • Organize, filter, and compress art assets to maximize performance while maintaining high quality
  • Use the Mono framework and C# to implement low-level enhancements that maximize memory usage and prevent garbage collection

Who this book is for

The book is intended for intermediate Unity game developers who wants to maximize the performance of their game. The book assumes familiarity with C# programming.

Publisher resources

Download Example Code

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. Unity Game OptimizationThird Edition
  3. Dedication
  4. About Packt
    1. Why subscribe?
  5. Contributors
    1. About the authors
    2. About the reviewer
    3. Packt is searching for authors like you
  6. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  7. Section 1: Base Scripting Optimization
  8. Evaluating Performance Problems
    1. Gathering profiling data using the Unity Profiler
      1. Launching the Profiler
        1. Editor or standalone instances
        2. Connecting to a WebGL instance
        3. Remote connection to an iOS device
        4. Remote connection to an Android device
        5. Editor profiling
      2. The Profiler window
        1. Profiler controls
          1. Add Profiler
          2. Playmode
          3. Record
          4. Deep Profile
          5. Allocation Callstack
          6. Clear
          7. Load
          8. Save
          9. Frame Selection
        2. Timeline View
        3. Breakdown View Controls
        4. Breakdown View
          1. The CPU Usage area
          2. The GPU Usage area
          3. The Rendering area
          4. The Memory area
          5. The Audio area
          6. The Physics 3D and Physics 2D areas
          7. The network messages and network operations areas
          8. The Video area
          9. The UI and UI Details areas
          10. The Global Illumination area
    2. Best approaches to performance analysis
      1. Verifying script presence
      2. Verifying script count
      3. Verifying the order of events
      4. Minimizing ongoing code changes
      5. Minimizing internal distractions
      6. Minimizing external distractions
      7. Targeted profiling of code segments
        1. Profiler script control
        2. Custom CPU profiling
    3. Final thoughts on profiling and analysis
      1. Understanding the Profiler
      2. Reducing noise
      3. Focusing on the issue
    4. Summary
  9. Scripting Strategies
    1. Obtaining components using the fastest method
    2. Removing empty callback definitions
    3. Caching component references
    4. Sharing calculation output
    5. Update, coroutines, and InvokeRepeating
    6. Faster GameObject null reference checks
    7. Avoid retrieving string properties from GameObjects
    8. Using appropriate data structures
    9. Avoiding re-parenting transforms at runtime
    10. Considering caching transform changes
    11. Avoiding Find() and SendMessage() at runtime
      1. Assigning references to pre-existing objects
      2. Static classes
      3. Singleton components
      4. A global messaging system
        1. A globally accessible object
        2. Registration
        3. Message processing
        4. Implementing the messaging system
        5. Message queuing and processing
        6. Implementing custom messages
        7. Message sending
        8. Message registration
        9. Message cleanup
        10. Wrapping up the messaging system
    12. Disabling unused scripts and objects
      1. Disabling objects by visibility
      2. Disabling objects by distance
    13. Using distance-squared over distance
    14. Minimizing deserialization behavior
      1. Reducing serialized object size
      2. Loading serialized objects asynchronously
      3. Keeping previously loaded serialized objects in memory
      4. Moving common data into ScriptableObjects
    15. Loading scenes additively and asynchronously
    16. Creating a custom Update() layer
    17. Summary
  10. Section 2: Graphical Optimizations
  11. The Benefits of Batching
    1. Draw calls
    2. Materials and shaders
    3. The Frame Debugger
    4. Dynamic batching
      1. Vertex attributes
      2. Mesh scaling
      3. Dynamic batching summary
    5. Static batching
      1. The Static flag
      2. Memory requirements
      3. Material references
      4. Static batching caveats
        1. Edit Mode debugging of static batching
        2. Instantiating static meshes at runtime
      5. Static batching summary
    6. Summary
  12. Optimizing Your Art Assets
    1. Audio
      1. Importing audio files
      2. Loading audio files
      3. Encoding formats and quality levels
      4. Audio performance enhancements
        1. Minimizing active audio source count
        2. Enabling Force to Mono for 3D sounds
        3. Resampling to lower frequencies
        4. Considering all compression formats
        5. Being cautious of streaming
        6. Applying filter effects through mixer groups to reduce duplication
        7. Using remote content streaming responsibly
        8. Consider using audio module files for background music
    2. Texture files
      1. Texture compression formats
      2. Texture performance enhancements
        1. Reducing texture file size
        2. Using mipmaps wisely
        3. Managing resolution downscaling externally
        4. Adjusting anisotropic filtering levels
        5. Consider atlasing
        6. Adjusting compression rates for nonsquare textures
        7. Sparse textures
        8. Procedural materials
        9. Asynchronous texture uploading
    3. Mesh and animation files
      1. Reducing the polygon count
      2. Tweaking mesh compression
      3. Using Read-Write Enabled appropriately
      4. Considering baked animations
      5. Combining meshes
    4. Asset bundles and resources
    5. Summary
  13. Faster Physics
    1. Understanding the physics engine
      1. Physics and time
        1. Maximum Allowed Timestep
        2. Physics updates and runtime changes
      2. Static colliders and dynamic colliders
      3. Collision detection
      4. Collider types
      5. The Collision Matrix
      6. Rigidbody active and sleeping states
      7. Ray and object casting
      8. Debugging physics
    2. Physics performance optimizations
      1. Scene setup
        1. Scaling
        2. Positioning
        3. Mass
      2. Using static colliders appropriately
      3. Using trigger volumes responsibly
      4. Optimizing the Collision Matrix
      5. Preferring discrete collision detection
      6. Modifying the fixed update frequency
      7. Adjusting the Maximum Allowed Timestep
      8. Minimizing raycasting and bounding-volume checks
      9. Avoiding complex Mesh Colliders
        1. Using simpler primitives
        2. Using simpler Mesh Colliders
      10. Avoiding complex physics components
      11. Letting physics objects sleep
      12. Modifying the solver iteration count
      13. Optimizing ragdolls
        1. Reducing joints and colliders
        2. Avoiding inter-ragdoll collisions
        3. Replacing, deactivating, or removing inactive ragdolls
      14. Knowing when to use physics
    3. Summary
  14. Dynamic Graphics
    1. Exploring the Rendering Pipeline
      1. The GPU frontend
      2. The GPU backend
        1. Fill Rate
          1. Overdraw
        2. Memory bandwidth
      3. Lighting and shadowing
        1. Forward Rendering
        2. Deferred Shading
        3. Vertex-Lit shading (legacy)
        4. Global Illumination
      4. Multithreaded Rendering
      5. Low-level rendering APIs
    2. Detecting performance issues
      1. Profiling rendering issues
      2. Brute force testing
    3. Rendering performance enhancements
      1. Enabling/disabling GPU skinning
      2. Reducing geometric complexity
      3. Reducing tessellation
      4. Employing GPU instancing
      5. Using mesh-based LOD
        1. Culling groups
      6. Making use of Occlusion Culling
      7. Optimizing Particle Systems
        1. Making use of Particle System culling
        2. Avoiding recursive Particle System calls
      8. Optimizing Unity UI
        1. Using more Canvases
        2. Separating objects between static and dynamic Canvases
        3. Disabling Raycast Target for non-interactive elements
        4. Hiding UI elements by disabling the parent Canvas component
        5. Avoiding Animator components
        6. Explicitly defining the event camera for World Space Canvases
        7. Don't use alpha to hide UI elements
        8. Optimizing ScrollRects
          1. Make sure to use a RectMask2D
          2. Disable Pixel Perfect for ScrollRects
          3. Manually stop ScrollRect motion
        9. Using empty UIText elements for full-screen interaction
        10. Checking the Unity UI source code
        11. Checking the documentation
      9. Shader optimization
        1. Consider using shaders intended for mobile platforms
        2. Using small data types
        3. Avoiding changing precision while swizzling
        4. Using GPU-optimized helper functions
        5. Disabling unnecessary features
        6. Removing unnecessary input data
        7. Exposing only necessary variables
        8. Reducing mathematical complexity
        9. Reducing texture sampling
        10. Avoiding conditional statements
        11. Reducing data dependencies
        12. Surface Shaders
        13. Use shader-based LOD
      10. Using less texture data
      11. Testing different GPU texture compression formats
      12. Minimizing texture swapping
      13. VRAM limits
        1. Preloading textures with hidden GameObjects
        2. Avoid texture thrashing
      14. Lighting optimization
        1. Using real-time shadows responsibly
        2. Using culling masks
        3. Using baked lightmaps
      15. Optimizing rendering performance for mobile devices
        1. Avoiding alpha testing
        2. Minimizing draw calls
        3. Minimizing Material count
        4. Minimizing texture size
        5. Making textures square and the power-of-two
        6. Using the lowest possible precision formats in shaders
    4. Summary
  15. Section 3: Advance Optimizations
  16. Optimizations for Virtual and Augmented Reality
    1. Overview of XR technology
    2. Developing XR products
      1. User comfort
    3. Performance enhancements in XR
      1. The kitchen sink
      2. Single Pass versus Multi Pass Stereo rendering
      3. Applying antialiasing
      4. Using forward rendering
      5. Applying image effects in VR
      6. Backface culling
      7. Spatialized audio
      8. Avoiding camera physics collisions
      9. Avoiding Euler angles
      10. Exercise restraint
      11. Keeping up to date with the latest developments
    4. Summary
  17. Masterful Memory Management
    1. The Mono platform
      1. Memory domains
        1. The stack
        2. The heap
      2. Garbage collection
        1. Memory fragmentation
        2. Garbage collection at runtime
        3. Threaded garbage collection
    2. Code compilation
      1. IL2CPP
    3. Profiling memory
      1. Profiling memory consumption
      2. Profiling memory efficiency
    4. Memory management performance enhancements
      1. Garbage collection tactics
      2. Manual JIT compilation
      3. Value types and reference types
        1. Pass by value and by reference
        2. Structs are value types
        3. Arrays are reference types
        4. Strings are immutable reference types
      4. String concatenation
        1. StringBuilder
        2. String formatting
      5. Boxing
      6. The importance of data layout
      7. Arrays from the Unity API
      8. Using InstanceIDs for dictionary keys
      9. foreach loops
      10. Coroutines
      11. Closures
      12. The .NET library functions
      13. Temporary work buffers
      14. Object pooling
      15. Prefab pooling
        1. Poolable components
        2. The Prefab pooling system
        3. Prefab pools
        4. Object spawning
        5. Instance prespawning
        6. Object despawning
        7. Prefab pool testing
        8. Prefab pooling and scene loading
        9. Prefab pooling summary
      16. IL2CPP optimizations
      17. WebGL optimizations
    5. Summary
  18. The Data-Oriented Technology Stack
    1. The problem of multithreading
      1. A small example
    2. The Unity Job System
      1. A basic job
      2. A more complex example
    3. The new ECS
      1. Mixing ECS and jobs
    4. The burst compiler
    5. Summary
  19. Tactical Tips and Tricks
    1. Editor hotkey tips
      1. Working with GameObjects
      2. Scene window
      3. Arrays
      4. Interface
      5. In-editor documentation
    2. Editor UI tips
      1. Script Execution Order
      2. Editor files
      3. The Inspector window
      4. The Project window
      5. The Hierarchy window
      6. The Scene and Game windows
      7. Playmode
    3. Scripting tips
      1. General
      2. Attributes
        1. Variable attributes
        2. Class attributes
      3. Logging
      4. Useful links
    4. Custom Editor scripts and menu tips
    5. External tips
    6. Other tips
    7. Summary
  20. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: Unity Game Optimization - Third Edition
  • Author(s): Dr. Davide Aversa, Chris Dickinson
  • Release date: November 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781838556518