Table Of ContentLearning C# by Developing
Games with Unity 2020
Fifth Edition
An enjoyable and intuitive approach to getting started with C#
programming and Unity
Harrison Ferrone
BIRMINGHAM - MUMBAI
Learning C# by Developing Games with
Unity 2020
Fifth Edition
Copyright © 2020 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.
Commissioning Editor: Pavan Ramchandani
Acquisition Editor: Ashitosh Gupta
Content Development Editor: Akhil Nair
Senior Editor: Hayden Edwards
Technical Editor: Deepesh Patel
Copy Editor: Safis Editing
Project Coordinator: Kinjal Bari
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Nilesh Mohite
First published: September 2013
Second edition: March 2016
Third edition: December 2017
Fourth edition: March 2019
Fifth edition: August 2020
Production reference: 1200820
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80020-780-6
www.packt.com
"If people reach perfection they vanish, you know."
The Once and Future King
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well
as industry leading tools to help you plan your personal development and advance your
career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.packt.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
customercare@packtpub.com for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.
Contributors
About the author
Harrison Ferrone was born in Chicago, IL, and was raised all over. Most days you can find
him writing technical documentation at Microsoft, creating instructional content for
LinkedIn Learning and Pluralsight, or tech editing for the Ray Wenderlich website.
He holds various fancy looking pieces of paper from the University of Colorado at Boulder
and Columbia College, Chicago. Despite being a proud alumnus, most of these are stored
in a basement somewhere.
After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he
fell into a teaching career and never looked back. Throughout all this, he's bought many
books, acquired a few cats, worked abroad, and continually wondered why Neuromancer
isn't on more course syllabi.
Completing this book wouldn't have been possible without the support of Kelsey, my
partner in crime on this journey, and Wilbur, Merlin, Walter, and Evey for their
courageous spirits and gracious hearts.
About the reviewers
Andrew Edmonds is an experienced programmer, game developer, and educator. He has a
Bachelor of Science degree in Computer Science from Washburn University and is a Unity
Certified Programmer and Instructor. After college, he worked as a software engineer for
the Kansas State Legislature for three years before spending the next five years teaching
high school kids how to write code and make video games. As a teacher, he helped many
young aspiring game developers achieve beyond what they ever thought possible,
including winning the SkillsUSA National Championship for video game development in
2019 with a virtual reality game made in Unity. Andrew lives in Washington with his wife,
Jessica, and daughters, Alice and Ada.
Adam Brzozowski is an experienced software engineer who develops games and client
applications. Working with Unity, Unreal Engine, C++, Swift, and Java, he finds the right
solution for each project.
Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit authors.packtpub.com
and apply today. We have worked with thousands of developers and tech professionals,
just like you, to help them share their insight with the global tech community. You can
make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.
Table of Contents
Preface 1
Chapter 1: Getting to Know Your Environment 7
Technical requirements 8
Getting started with Unity 2020 9
Using macOS 15
Creating a new project 17
Navigating the editor 18
Using C# with Unity 20
Working with C# scripts 20
Introducing the Visual Studio editor 22
Time for action – opening a C# file 22
Beware of naming mismatches 25
Syncing C# files 25
Exploring the documentation 26
Accessing Unity's documentation 26
Time for action – opening the Reference Manual 26
Time for action – using the Scripting Reference 27
Locating C# resources 29
Time for action – looking up a C# class 29
Summary 30
Pop quiz – dealing with scripts 31
Chapter 2: The Building Blocks of Programming 32
Defining variables 33
Names are important 34
Variables act as placeholders 34
Time for action – creating a variable 35
Time for action – changing a variable's value 37
Understanding methods 38
Methods drive actions 38
Methods are placeholders too 39
Time for action – creating a simple method 40
Introducing classes 41
A common Unity class 41
Classes are blueprints 42
Working with comments 43
Practical backslashes 43
Multi-line comments 43
Time for action – adding comments 44
Putting the building blocks together 45
Table of Contents
Scripts become components 45
A helping hand from MonoBehavior 46
Hero's trial – MonoBehavior in the Scripting API 47
Communication among classes 47
Summary 48
Pop quiz – C# building blocks 48
Chapter 3: Diving into Variables, Types, and Methods 49
Writing proper C# 50
Debugging your code 51
Declaring variables 52
Type and value declarations 52
Type-only declarations 53
Using access modifiers 54
Choosing a security level 54
Time for action – making a variable private 55
Working with types 55
Common built-in types 56
Time for action – playing with different types 57
Time for action – creating interpolated strings 58
Type conversions 59
Inferred declarations 60
Custom types 60
Types roundup 60
Naming variables 61
Best practices 61
Understanding variable scope 62
Introducing operators 64
Arithmetic and assignments 64
Time for action – executing incorrect type operations 66
Defining methods 67
Basic syntax 67
Modifiers and parameters 68
Time for action – defining a simple method 69
Naming conventions 70
Methods are logic detours 70
Specifying parameters 71
Time for action – adding method parameters 72
Specifying return values 73
Time for action – adding a return type 73
Using return values 74
Time for action – capturing return values 74
Hero's trial – methods as arguments 75
Dissecting common Unity methods 76
The Start method 76
The Update method 77
[ ii ]
Table of Contents
Summary 78
Pop quiz – variables and methods 78
Chapter 4: Control Flow and Collection Types 79
Selection statements 80
The if-else statement 80
Basic syntax 80
Time for action – thieving prospects 83
Using the NOT operator 85
Nesting statements 86
Evaluating multiple conditions 87
Time for action – reaching the treasure 88
The switch statement 90
Basic syntax 90
Pattern matching 91
Time for action – choosing an action 91
Fall-through cases 92
Time for action – rolling the dice 92
Pop quiz 1 – if, and, or but 94
Collections at a glance 94
Arrays 94
Basic syntax 95
Indexing and subscripts 96
Range exceptions 96
Lists 97
Basic syntax 97
Time for action – party members 98
Common methods 99
Dictionaries 100
Basic syntax 100
Time for action – setting up an inventory 101
Working with dictionary pairs 102
Pop quiz 2 – all about collections 103
Iteration statements 103
For loops 104
Time for action – finding an element 105
foreach loops 107
Looping through key-value pairs 108
Hero's trial – finding affordable items 109
while loops 109
Time for action – tracking player lives 110
To infinity and beyond 111
Summary 112
Chapter 5: Working with Classes, Structs, and OOP 113
Defining a class 114
Basic syntax 114
Time for action – creating a character class 114
Instantiating class objects 115
[ iii ]