Reader small image

You're reading from  Unity Game Optimization - Third Edition

Product typeBook
Published inNov 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781838556518
Edition3rd Edition
Languages
Tools
Right arrow
Authors (2):
Dr. Davide Aversa
Dr. Davide Aversa
author image
Dr. Davide Aversa

Dr. Davide Aversa holds a PhD in Artificial Intelligence (AI) and an MSc in AI and robotics from the University of Rome La Sapienza in Italy. He has a strong interest in AI for the development of interactive virtual agents and procedural content generation. He has served as a program committee member for video game-related conferences such as the IEEE conference on computational intelligence and games, and he also regularly participates in game-jam contests. He also writes a blog on game design and game development.
Read more about Dr. Davide Aversa

Chris Dickinson
Chris Dickinson
author image
Chris Dickinson

Chris Dickinson grew up in a quiet little corner of England with a strong passion for mathematics, science and, in particular, video games. He loved playing them, dissecting their gameplay, and trying to figure out how they worked. Watching his dad hack the hex code of a PC game to get around the early days of copy protection completely blew his mind! His passion for science won the battle at the time; however, after completing a master's degree in physics with electronics, he flew out to California to work in the field of scientific research in the heart of Silicon Valley. Shortly afterward, he had to admit to himself that research work was an unsuitable career path for his temperament. After firing resumes in all directions, he landed a job that finally set him on the correct course in the field of software engineering (this is not uncommon for physics grads, I hear). His time working as an automated tools developer for IPBX phone systems fit his temperament much better. Now he was figuring out complex chains of devices, helping its developers fix and improve them, and building tools of his own. Chris learned a lot about how to work with big, complex, real-time, event-based, user-input driven state machines (sounds familiar?). Being mostly self-taught at this point, Chris's passion for video games was flaring up again, pushing him to really figure out how video games were built. Once he felt confident enough, he returned to school for a bachelor's degree in game and simulation programming. By the time he was done, he was already hacking together his own (albeit rudimentary) game engines in C++ and regularly making use of those skills during his day job. However, if you want to build games, you should just build games, and not game engines. So, Chris picked his favorite publically available game engine at the time--an excellent little tool called Unity 3D--and started hammering out some games. After a brief stint of indie game development, Chris regretfully decided that the demands of that particular career path weren't for him, but the amount of knowledge he had accumulated in just a few short years was impressive by most standards, and he loved to make use of it in ways that enabled other developers with their creations. Since then, Chris has authored a tutorial book on game physics (Learning Game Physics with Bullet Physics and OpenGL, Packt Publishing) and two editions of a Unity performance optimization book (which you are currently reading). He has married the love of his life, Jamie, and works with some of the coolest modern technology as a software development engineer in Test (SDET) at Jaunt Inc. in San Mateo, CA, a Virtual Reality/Augmented Reality startup that focuses on delivering VR and AR experiences, such as 360 videos (and more!). Outside of work, Chris continues to fight an addiction to board games (particularly Battlestar: Galactica and Blood Rage), an obsession with Blizzard's Overwatch and Starcraft II, cater to the ever-growing list of demands from a pair of grumpy yet adorable cats, and gazing forlornly at the latest versions of Unity with a bunch of game ideas floating around on paper. Someday soon, when the time is right (and when he stops slacking off), his plans may come to fruition
Read more about Chris Dickinson

View More author details
Right arrow

Preface

User experience is a critical component of any game. This not only includes our game's story and its gameplay but also how smoothly the graphics run, how reliably the game connects to multiplayer servers, how responsive it is to user input, and even how large the final application file size is due to the prevalence of mobile devices and cloud downloads. The barrier of entry into game development has been lowered considerably thanks to tools such as Unity, which offer an enormous array of useful development features while still being accessible to individual developers. However, due to the amount of competition in the gaming industry, the level of quality of the final product that our players expect us to provide is increasing with every passing day. We should expect that players and critics can and will scrutinize every facet of our game.

The goals of performance optimization are deeply entwined with user experience. Poorly optimized games can result in low frame rates, freezes, crashes, input lag, long loading times, inconsistent and jittery runtime behavior, physics engine breakdowns, and even excessively high battery power consumption (an often-neglected metric for mobile devices). Having just one of these issues can be a game developer's worst nightmare as reviews will tend to focus on the one thing that we did poorly, ignoring all the things that we did well.

One goal of performance optimization is to make the best use of the available resources, including CPU resources such as the number of cycles consumed, how much main memory space we're using (known as RAM), as well as Graphics Processing Unit (GPU) resources, which includes its own memory space (known as VRAM), Fill Rate, Memory Bandwidth, and so on. However, the most important goal of performance optimization is to ensure that no single resource causes a bottleneck at an inappropriate time and that the highest priority tasks get taken care of first. Even small, intermittent hiccups and sluggishness in performance can pull the player out of the experience, breaking the game immersion and limiting our potential to create the experience we intended. Another consideration is that the more resources we can save, the more activity we can afford to implement in our games, allowing us to generate more exciting and dynamic gameplay.

It is also vital to decide when to take a step back and stop making performance enhancements. In a world with infinite time and resources, there will always be another way to make it better, faster, and more efficient. There must be a point during development where we decide that the product has reached an acceptable level of quality. If not, we risk dooming ourselves to repeatedly implementing changes that result in little or no tangible benefit, while each change also risks the chance that we introduce more bugs.

The best way to decide whether a performance issue is worth fixing is to answer the question, will the user notice it?. If the answer to this question is no, then performance optimization will be a wasted effort. There is an old saying in software development:

Premature optimization is the root of all evil.

Premature optimization is the cardinal sin of reworking and refactoring code to enhance performance without any proof that it is necessary. This can mean either making changes without showing that a performance problem even exists, or making changes because we only believe a performance issue might stem from a particular area before it has been proven to be true.

Of course, the original version of this common saying by Donald Knuth goes on to say that we should still write our code to avoid the more straightforward and obvious performance problems. However, the real performance optimization work toward the end of a project can take a lot of time, and we should plan the time to polish the product properly while avoiding the desire to implement more costly and time-consuming changes without any valid proof. These kinds of mistakes have cost software developers, as a collective whole, a depressing number of work hours for nothing.

This book intends to give you the tools, knowledge, and skills you need to both detect and fix performance issues in a Unity application, no matter where they stem from. These bottlenecks can appear within hardware components such as the CPU, GPU, and RAM, or within software subsystems such as physics, rendering, and the Unity engine itself.

Optimizing the performance of our games will give them a much better chance of succeeding and standing out from the crowd in a marketplace that is inundated with new, high-quality games every single day.

Who this book is for

The book is intended for game developers who want to learn optimization techniques for building high performant games with the latest Unity version.

What this book covers

Chapter 1, Evaluating Performance Problems, provides an exploration of the Unity Profiler and a series of methods to profile our application, detect performance bottlenecks, and perform root cause analysis.

Chapter 2, Scripting Strategies, deals with the best practices for our Unity C# script code, minimizing MonoBehaviour callback overhead, improving inter-object communication, and more.

Chapter 3, The Benefits of Batching, explores Unity's dynamic batching and static batching systems, and how they can be utilized to ease the burden on the rendering pipeline.

Chapter 4, Optimizing Your Art Assets, helps you to understand the underlying technology behind art assets and learn how to avoid common pitfalls with importing, compression, and encoding.

Chapter 5, Faster Physics, is about investigating the nuances of Unity's internal physics engines for both 3D and 2D games, and how to properly organize our physics objects for improved performance.

Chapter 6, Dynamic Graphics, provides an in-depth exploration of the rendering pipeline, and how to improve applications that suffer rendering bottlenecks in the GPU or CPU, how to optimize graphical effects such as lighting, shadows, and particle effects, ways in which to optimize shader code, and some graphics optimization specific for mobile devices.

Chapter 7, Optimizations for Virtual and Augmented Reality, focuses on the new entertainment mediums of VR and AR, and includes several techniques for optimizing performance that is unique to apps built for these platforms.

Chapter 8, Masterful Memory Management, examines the inner workings of the Unity engine, the Mono framework, and how memory is managed within these components to protect our application from excessive heap allocations and runtime garbage collection.

Chapter 9, The Data-Oriented Technology Stack, examines the new Unity optimizations for multithreading intensive games: DOTS. We introduce the new C# Job System, the new Unity ECS, and the burst compiler.

Chapter 10, Tactical Tips and Tricks, concludes the book with a multitude of useful techniques used by Unity professionals to improve project workflow and scene management.

To get the most out of this book

The majority of this book will focus on features and enhancements that apply to Unity 2019 and Unity 2020. Many of the techniques explored within this book can be applied to Unity 2018 projects and older, but some features may be different. These differences will be highlighted, where applicable.

It is worth noting that the code it is supposed to work on Unity 2020 but at the time of writing we could only test it on the alpha version. Additional incompatibilities may arise when Unity 2020 comes out of alpha.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packt.com.
  2. Select the Support tab.
  3. Click on Code Downloads.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Unity-Game-Optimization-Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "These can be accessed through the UnityEngine.Profiling.Profiler class through its BeginSample() and EndSample() methods."

A block of code is set as follows:

void DoSomethingCompletelyStupid() { 
Profiler.BeginSample("My Profiler Sample");
List<int> listOfInts = new List<int>();
for(int i = 0; i < 1000000; ++i) {
listOfInts.Add(i);
}
Profiler.EndSample();
}

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "When a Unity application is compiled in Development Mode."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Game Optimization - Third Edition
Published in: Nov 2019Publisher: PacktISBN-13: 9781838556518
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Dr. Davide Aversa

Dr. Davide Aversa holds a PhD in Artificial Intelligence (AI) and an MSc in AI and robotics from the University of Rome La Sapienza in Italy. He has a strong interest in AI for the development of interactive virtual agents and procedural content generation. He has served as a program committee member for video game-related conferences such as the IEEE conference on computational intelligence and games, and he also regularly participates in game-jam contests. He also writes a blog on game design and game development.
Read more about Dr. Davide Aversa

author image
Chris Dickinson

Chris Dickinson grew up in a quiet little corner of England with a strong passion for mathematics, science and, in particular, video games. He loved playing them, dissecting their gameplay, and trying to figure out how they worked. Watching his dad hack the hex code of a PC game to get around the early days of copy protection completely blew his mind! His passion for science won the battle at the time; however, after completing a master's degree in physics with electronics, he flew out to California to work in the field of scientific research in the heart of Silicon Valley. Shortly afterward, he had to admit to himself that research work was an unsuitable career path for his temperament. After firing resumes in all directions, he landed a job that finally set him on the correct course in the field of software engineering (this is not uncommon for physics grads, I hear). His time working as an automated tools developer for IPBX phone systems fit his temperament much better. Now he was figuring out complex chains of devices, helping its developers fix and improve them, and building tools of his own. Chris learned a lot about how to work with big, complex, real-time, event-based, user-input driven state machines (sounds familiar?). Being mostly self-taught at this point, Chris's passion for video games was flaring up again, pushing him to really figure out how video games were built. Once he felt confident enough, he returned to school for a bachelor's degree in game and simulation programming. By the time he was done, he was already hacking together his own (albeit rudimentary) game engines in C++ and regularly making use of those skills during his day job. However, if you want to build games, you should just build games, and not game engines. So, Chris picked his favorite publically available game engine at the time--an excellent little tool called Unity 3D--and started hammering out some games. After a brief stint of indie game development, Chris regretfully decided that the demands of that particular career path weren't for him, but the amount of knowledge he had accumulated in just a few short years was impressive by most standards, and he loved to make use of it in ways that enabled other developers with their creations. Since then, Chris has authored a tutorial book on game physics (Learning Game Physics with Bullet Physics and OpenGL, Packt Publishing) and two editions of a Unity performance optimization book (which you are currently reading). He has married the love of his life, Jamie, and works with some of the coolest modern technology as a software development engineer in Test (SDET) at Jaunt Inc. in San Mateo, CA, a Virtual Reality/Augmented Reality startup that focuses on delivering VR and AR experiences, such as 360 videos (and more!). Outside of work, Chris continues to fight an addiction to board games (particularly Battlestar: Galactica and Blood Rage), an obsession with Blizzard's Overwatch and Starcraft II, cater to the ever-growing list of demands from a pair of grumpy yet adorable cats, and gazing forlornly at the latest versions of Unity with a bunch of game ideas floating around on paper. Someday soon, when the time is right (and when he stops slacking off), his plans may come to fruition
Read more about Chris Dickinson