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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering Unity Scripting
Mastering Unity Scripting

Mastering Unity Scripting: Learn advanced C# tips and techniques to make professional-grade games with Unity

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.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

Mastering Unity Scripting

Chapter 2. Debugging

Debugging is the process of finding, identifying, and fixing bugs (errors or mistakes) in your code, and there are many ways to achieve this. To script effectively, you'll need to be aware of the most common workflows and toolsets available to you for debugging in Unity. Before considering them further, however, it's important to be aware of the general limitations of debugging and what it cannot achieve. Debugging is not a magical cure-all to remove all bugs and guarantee an error-free application. The computer scientist Edsger W. Dijkstra said, "Program testing can be used to show the presence of bugs, but never to show their absence". The crucial point is that during testing, you might encounter one or more errors. These errors can be identified, tested, and repaired through debugging. Yet, your tests—though perhaps extensive and careful—will never cover every possible case or scenario on every hardware platform under all...

Compilation errors and the console

Debugging typically refers to error-busting techniques for runtime use; that is, it refers to the things you can do to find and correct errors when your game is running. This understanding of debugging, of course, presupposes that your code is already valid and compiled. The implicit assumption is that you can write valid statements in C# and compile code, and you just want to find runtime errors that occur as a result of program logic. Thus, the focus is not on syntax but on logic, and this is indeed true. However, in this section, I'll speak very briefly about code compilation, about writing valid code, and using the console to find and correct errors of validity. This is important, both to introduce the Console window generally and also to establish a firm basis of thinking about debugging in more depth. Consider the following code sample 2-1 script file (ErrorScript.cs):

01 using UnityEngine;
02 using System.Collections;
03 
04 public class ErrorScript...

Debugging with Debug.Log – custom messages

Perhaps, the oldest and most well-known debugging technique in Unity is to use Debug.Log statements to print diagnostic messages to Console, thus illustrating program flow and object properties. This technique is versatile and appealing because it can be used in practically every Integrated Development Environment (IDE) and not just MonoDevelop. Further, all the Unity objects, including vector and color objects, have a convenient ToString function that allows their internal members (such as X, Y, and Z) to be printed to a human-readable string—one that can be easily sent to the console for debugging purposes. For example, consider the following code sample 2-3. This code sample demonstrates an important debugging workflow, namely, printing a status message about an object at its instantiation. This script, when attached to a scene object, prints its world position to Console, along with a descriptive message:

01 using UnityEngine;...

Overriding the ToString method

The following code sample 2-3 demonstrates the convenience of the ToString method when used in conjunction with the Debug.Log debugging. ToString lets you convert an object to a human-readable string that can be output to Console. In C#, every class inherits the ToString method by default. This means that using inheritance and polymorphism, you can override the ToString method of your class that customizes it as required and produce a more readable and accurate debug string that represents your class members. Consider the following code sample 2-4 that overrides ToString. If you get into the habit of overriding ToString for every class you make, your classes will become easier to debug:

using UnityEngine;
using System.Collections;
//--------------------------------------------
//Sample enemy Ogre class
public class EnemyOgre : MonoBehaviour 
{
//--------------------------------------------
//Attack types for OGRE
public enum AttackType {PUNCH, MAGIC, SWORD...

Visual debugging

Debugging with abstract or textual representations of data (such as Debug.Log) is often adequate but not always optimal. Sometimes, a picture is worth a thousand words. So, for example, when coding the line-of-sight functionality for enemies and other characters that allow them to see the player and other objects whenever they come in range, it's useful to get a live and graphical representation of where the line of sight actually is in the viewport. This line of functionality is drawn in terms of lines or as a wireframe cube. Similarly, if an object is following a path, it'd be great to draw this path in the viewport that displays it as a colored line. The purpose of this is not to create visual aids that will really show in the final game but simply to ease the debugging process that lets us get a better idea of how the game is working. These kinds of helpers or gizmos are a part of visual debugging. Unity already provides us with many gizmos automatically,...

Error logging

When you compile and build your game to distribute to testers, whether they're collected together in an office or scattered across the globe, you'll need a way to record errors and exceptions as and when they happen during gameplay. One way to do this is through logfiles. Logfiles are human-readable text files that are generated on the local computer by the game at runtime, and they record the details of errors as they occur, if any occur at all. The amount of information you record is a matter for careful consideration, as logging too much detail can obfuscate the file and too little can render the file useless. However, once a balance is reached the tester will be able to send you the log for inspection, and this will, hopefully, allow you to quickly pin-point errors in your code and repair them effectively, that is without introducing new errors! There are many ways to implement logging behavior in Unity. One way is using the native Application class to receive...

Compilation errors and the console


Debugging typically refers to error-busting techniques for runtime use; that is, it refers to the things you can do to find and correct errors when your game is running. This understanding of debugging, of course, presupposes that your code is already valid and compiled. The implicit assumption is that you can write valid statements in C# and compile code, and you just want to find runtime errors that occur as a result of program logic. Thus, the focus is not on syntax but on logic, and this is indeed true. However, in this section, I'll speak very briefly about code compilation, about writing valid code, and using the console to find and correct errors of validity. This is important, both to introduce the Console window generally and also to establish a firm basis of thinking about debugging in more depth. Consider the following code sample 2-1 script file (ErrorScript.cs):

01 using UnityEngine;
02 using System.Collections;
03 
04 public class ErrorScript...

Debugging with Debug.Log – custom messages


Perhaps, the oldest and most well-known debugging technique in Unity is to use Debug.Log statements to print diagnostic messages to Console, thus illustrating program flow and object properties. This technique is versatile and appealing because it can be used in practically every Integrated Development Environment (IDE) and not just MonoDevelop. Further, all the Unity objects, including vector and color objects, have a convenient ToString function that allows their internal members (such as X, Y, and Z) to be printed to a human-readable string—one that can be easily sent to the console for debugging purposes. For example, consider the following code sample 2-3. This code sample demonstrates an important debugging workflow, namely, printing a status message about an object at its instantiation. This script, when attached to a scene object, prints its world position to Console, along with a descriptive message:

01 using UnityEngine;
02 using System...

Overriding the ToString method


The following code sample 2-3 demonstrates the convenience of the ToString method when used in conjunction with the Debug.Log debugging. ToString lets you convert an object to a human-readable string that can be output to Console. In C#, every class inherits the ToString method by default. This means that using inheritance and polymorphism, you can override the ToString method of your class that customizes it as required and produce a more readable and accurate debug string that represents your class members. Consider the following code sample 2-4 that overrides ToString. If you get into the habit of overriding ToString for every class you make, your classes will become easier to debug:

using UnityEngine;
using System.Collections;
//--------------------------------------------
//Sample enemy Ogre class
public class EnemyOgre : MonoBehaviour 
{
//--------------------------------------------
//Attack types for OGRE
public enum AttackType {PUNCH, MAGIC, SWORD,...

Visual debugging


Debugging with abstract or textual representations of data (such as Debug.Log) is often adequate but not always optimal. Sometimes, a picture is worth a thousand words. So, for example, when coding the line-of-sight functionality for enemies and other characters that allow them to see the player and other objects whenever they come in range, it's useful to get a live and graphical representation of where the line of sight actually is in the viewport. This line of functionality is drawn in terms of lines or as a wireframe cube. Similarly, if an object is following a path, it'd be great to draw this path in the viewport that displays it as a colored line. The purpose of this is not to create visual aids that will really show in the final game but simply to ease the debugging process that lets us get a better idea of how the game is working. These kinds of helpers or gizmos are a part of visual debugging. Unity already provides us with many gizmos automatically, such as the...

Error logging


When you compile and build your game to distribute to testers, whether they're collected together in an office or scattered across the globe, you'll need a way to record errors and exceptions as and when they happen during gameplay. One way to do this is through logfiles. Logfiles are human-readable text files that are generated on the local computer by the game at runtime, and they record the details of errors as they occur, if any occur at all. The amount of information you record is a matter for careful consideration, as logging too much detail can obfuscate the file and too little can render the file useless. However, once a balance is reached the tester will be able to send you the log for inspection, and this will, hopefully, allow you to quickly pin-point errors in your code and repair them effectively, that is without introducing new errors! There are many ways to implement logging behavior in Unity. One way is using the native Application class to receive exception...

Editor debugging


It's sometimes claimed that Unity has no debugging tools built into the editor, but this is not quite true. With Unity, you can play your game and edit the scene at the same time while the game is running. You can even observe and edit properties in the Object Inspector, both private and public, as we saw earlier. This can give you a complete and graphical picture of your game at runtime; and allow you to detect and observe a wide range of potential errors. This form of debugging should not be underestimated. To get the most from in-editor debugging, activate the Debug mode from the Object Inspector by clicking on the context menu icon in the top-right corner of the inspector and then choose Debug from the menu, as shown here:

Accessing the Debug mode from the Object Inspector

Next, make sure that your viewports are configured appropriately so that they allow you to see both the Scene and Game views simultaneously during the Play mode, along with the Stats panel. To achieve...

Using the profiler


One additional tool that's used partly for debugging and partly for optimization is the Profiler window, which is available only in Unity Pro by clicking on the Profiler tab in Window in the application menu, as shown in the following screenshot. In short, the profiler gives you a statistical top-down view of how time and workload is distributed across the different parts of your game and across system hardware components, such as the CPU and graphics card. Using profiler, you can determine, for example, how much time is consumed by camera rendering in the scene compared to physics calculations or to audio functionality, as well as to other categories. It lets you measure performance, compare numbers, and assess where performance can be improved. The profiler is not really a tool that alerts you to the presence of bugs in your code specifically. However, if you're experiencing performance problems in running the game, such as lags and freezes, then it could guide you to...

Debugging with MonoDevelop – getting started


Earlier, we encountered the Debug.Log method of debugging to print helper messages to the console at critical moments in the code to help us see how the program executes. This method, while functional, however, suffers some significant drawbacks. First off, when writing larger programs with many Debug.Log statements it's easy to effectively "spam" the console with excessive messages. This makes it difficult to differentiate between the ones you need and the ones you don't. Second, it's generally a bad practice to change your code by inserting the Debug.Log statements simply to monitor program flow and find errors. Ideally, we should be able to debug without changing our code. Therefore, we have compelling reasons to find alternative ways to debug. MonoDevelop can help us here. Specifically, in the latest releases of Unity, MonoDevelop can natively attach itself to a running Unity process. In doing this, we get access to a range of common debugging...

Debugging with MonoDevelop – the Watch window


A Watch window allows you to view the value of a variable that's active in memory in the current step, and this includes both local and global variables. One way to quickly add a watch for a variable while it is in the break mode is to highlight it in the code editor and then hover your mouse over it. When you do this, leaving the mouse hovered for a few seconds, a pop-up window appears automatically. This window allows the full inspection of a variable, as shown in the following screenshot. You can contract and expand the members of a class and examine the state of all its variables.

Inspecting a variable with hover watches in the break mode

You can inspect practically all variable values for any active object using this hover method. However, typically, you'll want to place a more permanent watch on a variable and even a group of variables so that you can see their values collated together in a list. For this, you can use the Watch window docked...

Debugging with MonoDevelop – continue and stepping


After reaching a breakpoint and inspecting your code, it's likely that you'll want to exit from the break mode and continue program execution in some way. You might want to continue program execution, which effectively hands program control back to Unity. This allows the execution to continue as normal, until it meets the next breakpoint, if any. This method effectively resumes execution as normal, and it'll never pause again unless a new breakpoint is encountered. To continue in this way from MonoDevelop, press the F5 key or press the play button from the MonoDevelop toolbar. Otherwise, choose the Continue Debugging option in Run from the MonoDevelop application menu, as shown here:

Exiting the break mode and resuming with Continue Debugging

There are many occasions, however, where you don't want to continue execution in this way. Instead, you want to step execution over the lines of code, line by line, evaluating each line as it progresses...

Left arrow icon Right arrow icon

Description

Mastering Unity Scripting is an advanced book intended for students, educators, and professionals familiar with the Unity basics as well as the basics of scripting. Whether you've been using Unity for a short time or are an experienced user, this book has something important and valuable to offer to help you improve your game development workflow.

What you will learn

  • Understand core C# concepts, such as class inheritance, interfaces, singletons, and static objects
  • Implement effective Artificial Intelligence for NPCs
  • Work with eventdriven programming to optimize your code
  • Develop solid debugging and diagnostic techniques
  • Get to know the Mono Framework and Linq in practical contexts
  • Customize the rendering functionality for postprocess effects
  • Code line of sight, view testing, and other useful algorithms
  • Improve the quality of your code with the help of concepts such as attributes

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 29, 2015
Length: 380 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390563
Vendor :
Unity Technologies
Languages :
Concepts :
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 : Jan 29, 2015
Length: 380 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390563
Vendor :
Unity Technologies
Languages :
Concepts :
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 103.97
Mastering Unity Scripting
€41.99
Unity AI Programming Essentials
€24.99
Unity Game Development Scripting
€36.99
Total 103.97 Stars icon

Table of Contents

11 Chapters
1. Unity C# Refresher Chevron down icon Chevron up icon
2. Debugging Chevron down icon Chevron up icon
3. Singletons, Statics, GameObjects, and the World Chevron down icon Chevron up icon
4. Event-driven Programming Chevron down icon Chevron up icon
5. Cameras, Rendering, and Scenes Chevron down icon Chevron up icon
6. Working with Mono Chevron down icon Chevron up icon
7. Artificial Intelligence Chevron down icon Chevron up icon
8. Customizing the Unity Editor Chevron down icon Chevron up icon
9. Working with Textures, Models, and 2D Chevron down icon Chevron up icon
10. Source Control and Other Tips 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.5
(14 Ratings)
5 star 57.1%
4 star 35.7%
3 star 7.1%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Robert Kleszczynski Mar 09, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Coming from a self-taught programming background, I've seen a bunch of books tackle the basics of coding in Unity. Short of going through the documentation, there is not much out there to take people to the next level.This book serves as a bridge between the beginner concepts and the more advanced programming concepts covered in other books. While it does provide a short primer on C#, it's definitely recommended that you know the basics of programming before diving in. The book takes you through some of the more in depth functions in Mono Develop as well as some more practical uses of the language other than just syntax and other basics, which many books do a good job of covering already.The next steps included in this book are event-driven programming, camera manipulation and rendering, an introduction to artificial intelligence and enemy behavior, customizing Unity to fit your needs, and even a primer on working in two dimensions with Unity. Overall, I'd say I'm happy with the topics covered as they give a good foundation to move on to more advanced programming topics, like artificial intelligence.The explanations are clear and the code examples are pretty easy to go through without ripping your hair out. I'd definitely recommend it to anyone who is looking to take their next step into programming with Unity after knowing the basics.To better describe the code examples,, this book mainly focuses on tools and techniques to make your game programming a smoother process. There is a complete game covered in one of the chapters, but for the most part, the book provides working examples of elements that you can incorporate into your own projects.
Amazon Verified review Amazon
Jlthorne Jan 20, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great Transaction, Good book
Amazon Verified review Amazon
Thomas Feucht Apr 18, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recently have had the opportunity to review the book Mastering Unity Scripting by Alan Thorn, which was released in January 2015. In my opinion this intermediate to advanced level programming book requires you to have a basic understanding of C# and Unity 4.x in general. In my review I will take you through all 10 chapters of the book which contains 361 pages in total:1. Unity C# RefresherThis chapter gives an in-depth look at how to create C# scripts including advanced topics like enums, arrays, events, polymorphism, properties and more. The chapter is very useful to get your C# knowledge to the expert level.2. DebuggingThe second chapter will show you how to debug your C# code within the Mono IDE which comes with Unity including using the profiler for optimization.3. Singletons, Statics, GameObjects, and the WorldThis chapter covers the anatomy of both scenes and objects and how the interobject communication happens.4. Event-Driven ProgrammingIn this chapter you learn how event-driven programming helps you to create code that is easier to maintain and also with better performance.5. Cameras, Rendering, and ScenesThis chapter demonstrates how to create cameras for certain gameplay types like perspective and orthographic cameras, camera shakes and follow cameras. It also shows how camera rendering and postprocessing works.6. Working with MonoThe 6th chapter covers how to use lists and collections (dictionaries, stacks, enumerators), strings, regular expressions, linq and text Assets from the Mono Framework.7. Artificial IntelligenceIf you need to implement an articifial intelligence for your game, this chapter is for you. It's about creating a first-person sample game set inside a maze environment. Here, the player can attack enemies, and enemies can attack the player. The enemy will search the environment, look for the player, and when they are found, chase and attack them. The enemy can also be attacked, and when attacked, they will flee and search for power-ups if their health runs low.8. Customizing the Unity EditorThis chapter covers how to extend the Unity Editor with your own scripts: Batch Renaming of game objects, color blending, property exposing, localization.9. Working with Textures, Models, and 2DChapter 9 covers how work with rotating skybox backgrounds, procedural geometry, real-time editing of meshes and animation of mesh UVs.10. Source Control and Other TipsThe last chapter is about git as a source control system and contains other several tips and tricks. These other tips and tricks are about resources folder and external files, AssetBundles, persistent data and saved games.SummaryOverall this is a great in-depth guide to advanced Unity topics. It doesn't cover the basics well, but I think if you do the learning videos of Unity's web site first and afterwards start reading this book, then you take your Unity programming skills to the next level. I really liked the usage of C# instead of JavaScript for Unity Scripting, because I prefer C# over JavaScript.
Amazon Verified review Amazon
Roberto Dillon Feb 27, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Here we have a very nicely done Unity book for intermediate users. While "Mastering Unity Scripting" start with a recap chapter on Unity basics, this is only meant as a quick refresh and not as a full scale introduction so, if you are a beginner, check other titles before getting into this.After this, the book goes on by covering some fundamental ground that intermediate users should definitely know to push their skills to the next, advanced level, starting with debugging, using and finding game objects effectively, using lists and so on.There is also an introductory chapter on AI covering path finding and finite state machine in mecanim that I found a good read. Recommended.
Amazon Verified review Amazon
Bartleby47 Oct 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very useful stuff. Definitely recommend it.
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.