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
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781785888458
Vendor :
Unity Technologies
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 164.97
Unity 5.x Cookbook
$60.99
Unity 5  Game Optimization
$48.99
Procedural Content Generation for Unity Game Development
$54.99
Total $ 164.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.