Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Unity 5  Game Optimization
Unity 5  Game Optimization

Unity 5 Game Optimization: Master performance optimization for Unity3D applications with tips and techniques that cover every aspect of the Unity3D Engine

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Unity 5 Game Optimization

Chapter 2. Scripting Strategies

Since scripting will consume a great deal of our development time, it will be enormously beneficial to learn some best practices. Scripting is a very broad term, so we will try to limit our exposure in this chapter to situations that are very Unity specific, focusing on problems arising from within the Unity APIs and engine design. We will discuss the nuances and advanced topics of the C# language, .NET library, and Mono Framework, in Chapter 7, Masterful Memory Management.

Whether you have some specific problems in mind that you wish to solve or you just want to learn some techniques for future reference, this chapter will introduce you to an array of methods that you can use to improve your scripting efforts now and in the future. In each case, we will explore how and why the performance issue arises, an example situation in which the problem is occurring, and one or more solutions to combat the issue.

Cache Component references

A common mistake when scripting in Unity is to overuse the GetComponent() method. For example, the following script code is trying to check a creature's health value, and if its health goes below 0, disable a series of Components to prepare it for a death animation:

void TakeDamage() {
  if (GetComponent<HealthComponent>().health < 0) {
    GetComponent<Rigidbody>().enabled = false;
    GetComponent<Collider>().enabled = false;
    GetComponent<AIControllerComponent>().enabled = false;
    GetComponent<Animator>().SetTrigger("death");
  }
}

Each time this method executes, it will reacquire five different Component references. This is good in terms of heap memory consumption (in that it doesn't cost any), but it is not very friendly on CPU usage. This is particularly problematic if the main method were called during Update(). Even if it is not, it still might coincide with other important events, such as creating...

Obtaining Components using the fastest method

There are several variations of the GetComponent() method, and it becomes prudent to call the fastest possible version of this method. The three overloads available are GetComponent(string), GetComponent<T>(), and GetComponent(typeof(T)). It turns out that the fastest version depends on which version of Unity we are running.

In Unity 4, the GetComponent(typeof(T)) method is the fastest of the available options by a reasonable margin. Let's prove this with some simple testing:

int numTests = 1000000;
TestComponent test;

using (new CustomTimer("GetComponent(string)", numTests)) {
  for (var i = 0; i < numTests; ++i) {
    test = (TestComponent)GetComponent("TestComponent");
  }
}

using (new CustomTimer("GetComponent<ComponentName>", numTests)) {
  for (var i = 0; i < numTests; ++i) {
    test = GetComponent<TestComponent>();
  }
}

using (new CustomTimer("GetComponent(typeof(ComponentName...

Removing empty callback declarations

When we create new MonoBehaviour script files in Unity, whether we're using Unity 4 or Unity 5, it creates two boilerplate methods for us:

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

The Unity engine hooks in to these methods during initialization and adds them to a list of methods to call back at key moments. However, if we leave these as empty declarations in our codebase, then they will cost us a small overhead whenever the engine invokes them.

The Start() method is only called when the GameObject is instantiated for the first time, which can be whenever the scene is loaded or a new GameObject is instantiated from a Prefab. Therefore, leaving the empty Start() declaration may not be particularly noticeable unless there's a lot of GameObjects in the scene invoking them at startup time. However, it also adds unnecessary overhead to any GameObject.Instantiate() call, which typically...

Avoiding the Find() and SendMessage() methods at runtime

The SendMessage() method and family of GameObject.Find() methods are notoriously expensive, and should be avoided at all costs. The SendMessage() method is about 2,000 times slower than a simple function call, and the cost of the Find() method scales very poorly with Scene complexity since it must iterate through every GameObject in the Scene. It is sometimes reasonable to call Find() during initialization of a Scene, such as Awake() and Start(), only for objects that already exists in the Scene. However, using either method for inter-object communication at runtime is likely to generate a very noticeable overhead.

Relying on Find() and SendMessage() type methods is typically symptomatic of poor design, inexperience in programming with C# and Unity, or just plain laziness during prototyping. Their usage has become something of an epidemic among beginner- and intermediate-level projects, such that Unity Technologies feels the need to...

Disabling unused scripts and objects

Scenes can get pretty busy sometimes, especially when we're building large, open worlds. The more objects invoking code in an Update() method, the worse things will scale and the slower your game becomes. However, much of what is being processed may be completely unnecessary if it is outside of the player's view or simply too far away to matter. This may not be a possibility in large city-building simulation games where the entire simulation must be processed at all times, but it is often possible in first person and racing games, where the player is wandering around a large expansive area, where non-visible objects can be temporarily disabled without having any noticeable effect on gameplay.

Disabling objects by visibility

Sometimes, we want Components or GameObjects to be disabled when they're not visible. Unity comes with built-in rendering features to avoid rendering objects that are not visible by Cameras (Frustum Culling, which is...

Cache Component references


A common mistake when scripting in Unity is to overuse the GetComponent() method. For example, the following script code is trying to check a creature's health value, and if its health goes below 0, disable a series of Components to prepare it for a death animation:

void TakeDamage() {
  if (GetComponent<HealthComponent>().health < 0) {
    GetComponent<Rigidbody>().enabled = false;
    GetComponent<Collider>().enabled = false;
    GetComponent<AIControllerComponent>().enabled = false;
    GetComponent<Animator>().SetTrigger("death");
  }
}

Each time this method executes, it will reacquire five different Component references. This is good in terms of heap memory consumption (in that it doesn't cost any), but it is not very friendly on CPU usage. This is particularly problematic if the main method were called during Update(). Even if it is not, it still might coincide with other important events, such as creating particle effects,...

Obtaining Components using the fastest method


There are several variations of the GetComponent() method, and it becomes prudent to call the fastest possible version of this method. The three overloads available are GetComponent(string), GetComponent<T>(), and GetComponent(typeof(T)). It turns out that the fastest version depends on which version of Unity we are running.

In Unity 4, the GetComponent(typeof(T)) method is the fastest of the available options by a reasonable margin. Let's prove this with some simple testing:

int numTests = 1000000;
TestComponent test;

using (new CustomTimer("GetComponent(string)", numTests)) {
  for (var i = 0; i < numTests; ++i) {
    test = (TestComponent)GetComponent("TestComponent");
  }
}

using (new CustomTimer("GetComponent<ComponentName>", numTests)) {
  for (var i = 0; i < numTests; ++i) {
    test = GetComponent<TestComponent>();
  }
}

using (new CustomTimer("GetComponent(typeof(ComponentName))", numTests))  {
  for (var i ...

Removing empty callback declarations


When we create new MonoBehaviour script files in Unity, whether we're using Unity 4 or Unity 5, it creates two boilerplate methods for us:

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

The Unity engine hooks in to these methods during initialization and adds them to a list of methods to call back at key moments. However, if we leave these as empty declarations in our codebase, then they will cost us a small overhead whenever the engine invokes them.

The Start() method is only called when the GameObject is instantiated for the first time, which can be whenever the scene is loaded or a new GameObject is instantiated from a Prefab. Therefore, leaving the empty Start() declaration may not be particularly noticeable unless there's a lot of GameObjects in the scene invoking them at startup time. However, it also adds unnecessary overhead to any GameObject.Instantiate() call, which typically happens during...

Avoiding the Find() and SendMessage() methods at runtime


The SendMessage() method and family of GameObject.Find() methods are notoriously expensive, and should be avoided at all costs. The SendMessage() method is about 2,000 times slower than a simple function call, and the cost of the Find() method scales very poorly with Scene complexity since it must iterate through every GameObject in the Scene. It is sometimes reasonable to call Find() during initialization of a Scene, such as Awake() and Start(), only for objects that already exists in the Scene. However, using either method for inter-object communication at runtime is likely to generate a very noticeable overhead.

Relying on Find() and SendMessage() type methods is typically symptomatic of poor design, inexperience in programming with C# and Unity, or just plain laziness during prototyping. Their usage has become something of an epidemic among beginner- and intermediate-level projects, such that Unity Technologies feels the need to...

Disabling unused scripts and objects


Scenes can get pretty busy sometimes, especially when we're building large, open worlds. The more objects invoking code in an Update() method, the worse things will scale and the slower your game becomes. However, much of what is being processed may be completely unnecessary if it is outside of the player's view or simply too far away to matter. This may not be a possibility in large city-building simulation games where the entire simulation must be processed at all times, but it is often possible in first person and racing games, where the player is wandering around a large expansive area, where non-visible objects can be temporarily disabled without having any noticeable effect on gameplay.

Disabling objects by visibility

Sometimes, we want Components or GameObjects to be disabled when they're not visible. Unity comes with built-in rendering features to avoid rendering objects that are not visible by Cameras (Frustum Culling, which is automatic in all...

Consider using distance-squared over distance


It is safe to say that CPUs are relatively good at multiplying floating-point numbers together, but relatively dreadful at calculating square roots from them. Every time we ask a Vector3 to calculate a distance with the magnitude property or with the Distance() method, we're asking it to perform a square root calculation (as per the Pythagorean theorem), which can cost a lot of CPU overhead compared to many other types of vector math calculations.

However, the Vector3 class also offers a sqrMagnitude property, which is the same as distance, only squared. This lets us perform essentially the same comparison check without the expensive square root included, so long as we also square the value we're trying to compare it against; or, to describe this mathematically, if the magnitude of A is less than the magnitude of B, then A2 will be less than B2.

For example, consider code like the following:

float distance = (transform.position – other.transform...
Left arrow icon Right arrow icon

Key benefits

  • Optimize CPU cycles, memory usage, and GPU throughput for any Unity3D application
  • Master optimization techniques across all Unity Engine features including Scripting, Asset Management, Physics, Graphics Features, and Shaders
  • A practical guide to exploring Unity Engine's many performance-enhancing methods

Description

Competition within the gaming industry has become significantly fiercer in recent years with the adoption of game development frameworks such as Unity3D. Through its massive feature-set and ease-of-use, Unity helps put some of the best processing and rendering technology in the hands of hobbyists and professionals alike. This has led to an enormous explosion of talent, which has made it critical to ensure our games stand out from the crowd through a high level of quality. A good user experience is essential to create a solid product that our users will enjoy for many years to come. Nothing turns gamers away from a game faster than a poor user-experience. Input latency, slow rendering, broken physics, stutters, freezes, and crashes are among a gamer's worst nightmares and it's up to us as game developers to ensure this never happens. High performance does not need to be limited to games with the biggest teams and budgets. Initially, you will explore the major features of the Unity3D Engine from top to bottom, investigating a multitude of ways we can improve application performance starting with the detection and analysis of bottlenecks. You'll then gain an understanding of possible solutions and how to implement them. You will then learn everything you need to know about where performance bottlenecks can be found, why they happen, and how to work around them. This book gathers a massive wealth of knowledge together in one place, saving many hours of research and can be used as a quick reference to solve specific issues that arise during product development.

Who is this book for?

This book is intended for intermediate and advanced Unity developers who have experience with most of Unity's feature-set, and who want to maximize the performance of their game. Familiarity with the C# language will be needed.

What you will learn

  • Use the Unity Profiler to find bottlenecks anywhere in our application, and discover how to resolve them
  • Implement best-practices for C# scripting to avoid common pitfalls
  • Develop a solid understanding of the rendering pipeline, and maximize its performance through reducing draw calls and avoiding fill rate bottlenecks
  • Enhance shaders in a way that is accessible to most developers, optimizing them through subtle yet effective performance tweaks
  • Keep our scenes as dynamic as possible by making the most of the Physics engine
  • Organize, filter, and compress our art assets to maximize performance while maintaining high quality
  • Pull back the veil on the Mono Framework and the C# Language to implement low-level enhancements that maximize memory usage and avoid garbage collection
  • Get to know the best practices for project organization to save time through an improved workflow

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 06, 2015
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781785884580
Vendor :
Unity Technologies
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 06, 2015
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781785884580
Vendor :
Unity Technologies
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 124.97
Unity 5.x Cookbook
€45.99
Unity 5  Game Optimization
€36.99
Procedural Content Generation for Unity Game Development
€41.99
Total 124.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Detecting Performance Issues Chevron down icon Chevron up icon
2. Scripting Strategies Chevron down icon Chevron up icon
3. The Benefits of Batching Chevron down icon Chevron up icon
4. Kickstart Your Art Chevron down icon Chevron up icon
5. Faster Physics Chevron down icon Chevron up icon
6. Dynamic Graphics Chevron down icon Chevron up icon
7. Masterful Memory Management Chevron down icon Chevron up icon
8. Tactical Tips and Tricks Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(7 Ratings)
5 star 71.4%
4 star 14.3%
3 star 0%
2 star 0%
1 star 14.3%
Filter icon Filter
Top Reviews

Filter reviews by




BM Dec 16, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The author knows the subject inside-out and has done a great job in putting across concepts in a clear and concise way. The book is well organized and goes into great detail about different aspects of optimization. The tips and techniques mentioned in the book helped my game go from 25 fps (frames per second) to 55 fps in just a week!
Amazon Verified review Amazon
J JOAN LINARES PELLICER Dec 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been working with Unity for many years and a common problem we always have sooner or later is optimization. There are many tutorials, posts and articles out there with valuable information on how to optimize your Unity app, but they are not complete and difficult to collect.Chris in this Unity 5 Game Optimization has done a fantastic job putting into one book all the best techniques and suggestions to make your Unity game a success, considering all the different aspects your game can be optimized.A must have for intermediate-advanced unity developers.
Amazon Verified review Amazon
Daniel Thomas Jan 04, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Pros:* Covers all areas of optimization. Scripting, Batching, Art and Sound assets, Physics, Graphics and memory management.* Always careful to show how to test if optimizations worth doing.* Highlights differences between mobile and desktop optimizations.* Includes chapter on using the Profiler that is now free in Unity 5 Personal.Cons:* Some topics covered more than once although this is probably more noticeable as I read book cover to cover rather than just cherry picking chapters.* A few sections quite wordy and felt they could be shorter.Whilst I don't yet have a project ready to use most of the topics covered in this book I will definitely be coining back to it again when I do.
Amazon Verified review Amazon
Matt Thomas Dec 01, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very, very well written and thorough. The author is clearly a member of the Unity community, attends the conferences, reads the forums & Stack Overflow, and is a power user. I finished the book in two days and took copious notes. This book is intended for an intermediate Unity programmer who wants to learn about a multitude of optimization techniques. Instead of regurgitating the manual, the author does a great job of pulling together information from disparate sources and presenting it in an extremely clear and friendly manner. One of the best Unity books out there.
Amazon Verified review Amazon
Amazon Customer Aug 31, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Perfect book. I'm satisfied.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.