Learning C# by Developing Games with Unity 2019 - Harrison Ferrone - E-Book

Learning C# by Developing Games with Unity 2019 E-Book

Harrison Ferrone

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learning to program in today’s technical landscape can be a daunting task, especially when faced with the sheer number of languages you have to choose from. Luckily, Learning C# with Unity 2019 removes the guesswork and starts you off on the path to becoming a confident, and competent, programmer using game development with Unity.
You’ll start off small by learning the building blocks of programming, from variables, methods, and conditional statements to classes and object-oriented systems. After you have the basics under your belt you’ll explore the Unity interface, creating C# scripts, and translating your newfound knowledge into simple game mechanics.
Throughout this journey, you’ll get hands-on experience with programming best practices and macro-level topics such as manager classes and flexible application architecture. By the end of the book, you’ll be familiar with intermediate C# topics like generics, delegates, and events, setting you up to take on projects of your own.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 322

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Learning C# by Developing Games with Unity 2019Fourth Edition
Code in C# and build 3D games with Unity
Harrison Ferrone
BIRMINGHAM - MUMBAI

Learning C# by Developing Games with Unity 2019Fourth Edition

Copyright © 2019 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.

Acquisition Editor: Karan GuptaContent Development Editor: Pranay FereiraTechnical Editor: Ralph RosarioCopy Editor:Safis EditingProject Coordinator: Pragati ShuklaProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Alishon MendonsaProduction Coordinator:Nilesh Mohite

First published: September 2013 Second edition: March 2016 Third edition: December 2017 Fourth edition: March 2019

Production reference: 2170620

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78953-205-0

www.packtpub.com

To Kelsey, my partner in crime and loving companion on this journey. To Wilbur, Merlin, Walter, and Evey for their courageous spirits and gracious hearts.
– Harrison Ferrone
mapt.io

Mapt is an online digital library that gives you full access to over 5,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

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

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 [email protected] 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 raised all over. Most days, you can find him 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 allthis,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 my partner Kelsey, my sounding board, Basel Farag, and my family.

About the reviewer

Dr. Davide Aversa holds a Ph.D. in Artificial Intelligence and an M.Sc. in Artificial Intelligence and Robotics from the University of Rome "La Sapienza" in Italy. He has a strong interest in Artificial Intelligence for the development of Interactive Virtual Agents and Procedural Content Generation (PCG). He serves at the PC of video game-related conferences such as the IEEE Conference on Computational Intelligence and Games (CIG) and he also is regularly participating in game-jam contests. He also writes a blog on game design and game development.

Luiz Henrique Bueno is a Certified ScrumMaster (CSM) and Unity Certified Developer with over 29 years of experience in software development.

In 2002, he wrote the book Web Applications with Visual Studio.NET, ASP.NET, and C#, at the time of the launch of Visual Studio.NET.

He's worked as a Chief Editor at Casa Conectada, a magazine about smart homes. For six years, he's developed projects using Crestron and Control4.

In 2017, he worked as a reviewer on the book Unity 2017 Game Optimization, Second Edition, published by Packt.

Since 2010, he's been developing apps and games, including VR/AR and voice applications, using Unity, C#, Xcode, Obj-C, Swift, AWS, Node.js, and Alexa Skills.

His motto is "Do not write code for QA, write code for production." You can reach him on Twitter at @hackingwithrick.

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

Title Page

Copyright and Credits

Learning C# by Developing Games with Unity 2019 Fourth Edition

Dedication

About Packt

Why subscribe?

Packt.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Downloading the Example Code Files

Downloading the Color Images

Conventions Used

Sections

Time for Action

What just happened?

Pop Quiz – Heading

Hero's Trial – Heading

Get in Touch

Reviews

Section 1: Programming Foundations and C#

Getting to Know your Environment

Some basic prerequisites

Starting out with Unity 2019

Creating a new project

Navigating the editor

Using C# with Unity

Working with C# scripts

Time for action – creating a C# script

Introducing the Visual Studio editor

Time for action – opening a C# file

Beware of naming mismatches

Syncing C# files

Fixing a broken sync

Documentation

Accessing Unity's documentation

Time for action – opening the Reference Manual

Time for action – using the Scripting Reference

Locating C# resources

Time for action – looking up a C# class

Pop quiz – dealing with scripts

Summary

The Building Blocks of Programming

Defining variables

Names are important

Variables act as placeholders

Time for action – creating a variable

Time for action – changing a variable's value

A method to the madness

Methods drive actions

Methods are placeholders too

Time for action – a simple method

Introducing classes

A class all along

Everyday blueprints

Commenting is key

Practical backslashes

Time for action – adding comments

Putting it together in Unity

Scripts become components

Variables and the Inspector panel

A helping hand from MonoBehavior

Hero's trial – MonoBehavior in the Scripting API

Class and component communication

Enter dot notation

Pop quiz – C# building blocks

Summary

Diving into Variables,Types, and Methods

Writing proper C#

Simple debugging

Variable syntax

Type and value declarations

Type-only declarations

Access modifiers

Choosing a security level

Time for action – making a variable private

Working with types

Common built-in types

Time for action – playing with different types

Time for action – creating interpolated strings

Type conversions

Inferred declarations

Custom types

Types roundup

Naming variables

Best practices

Variable scope

Introducing operators

Arithmetic and assignments

Time for action – executing incorrect type operations

Pop quiz #1 – variables and types

Defining methods

Basic syntax

Modifiers and parameters

Time for action – defining a simple method

Naming conventions

Methods are logic detours

Specifying parameters

Assigning arguments

Time for action – adding method parameters

Specifying return values

Time for action – adding a return type

Using return values

Time for action – capturing return values

Hero's trial – methods as arguments

Common Unity methods

The Start method

The Update method

Pop quiz #2 – Understanding methods

Summary

Control Flow and Collection Types

Selection statements

The if-else statement

Basic syntax

Time for action – thieving prospects

Using the NOT operator

Nesting statements

Evaluating multiple conditions

Time for action – reaching the treasure

The switch statement

Basic syntax

Pattern matching

Time for action – choosing an action

Fall-through cases

Time for action – rolling the dice

Pop quiz #1 – If, and, or but

Collections at a glance

Arrays

Basic syntax

Indexing and subscripts

Range exceptions

Lists

Basic syntax

Time for action – party members

Common methods

Dictionaries

Basic syntax

Time for action – setting up an inventory

Working with dictionary pairs

Pop quiz #2 – all about collections

Iteration statements

For loops

Time for action – finding an element

The foreach loops

Looping through key-value pairs

Hero's trial – finding affordable items

The while loops

Time for action – tracking player lives

To infinity and beyond

Summary

Working with Classes, Structs, and OOP

Defining a class

Basic syntax

Time for action – creating a character class

Instantiating class objects

Time for action – creating a new character

Adding class fields

Time for action – fleshing out character details

Using constructors

Time for action – specifying starting properties

Declaring class methods

Time for action – printing out character data

What's a struct?

Basic syntax

Time for action – creating a weapon struct

Classes vs structs

Reference types

Time for action – creating a new hero

Value types

Time for action – copying weapons

The Object-Oriented mindset

Encapsulation

Time for action – adding a reset

Inheritance

Base constructors

Time for action – calling a base constructor

Composition

Polymorphism

Time for action – functional variations

OOP roundup

Applying OOP in Unity

Objects are a class act

Accessing components

Basic syntax

Time for action – accessing the current transform component

Finding GameObjects

Time for action - finding components on different objects

Drag and drop

Time for action – assigning variables in Unity

Pop quiz: all things OOP

Summary

Section 2: Scripting Game Mechanics in Unity

Getting Your Hands Dirty with Unity

A game design primer

Game design documents

The Hero Born one-page

Building a level

Creating primitives

Time for action – creating a ground plane

Thinking in 3D

Materials

Time for action – changing the ground color

White-boxing

Editor tools

Hero's Trial – putting up drywall

Keeping the Hierarchy clean

Time for action – using empty objects

Working with prefabs

Time for action – creating a turret

Time for action – updating the prefab

Time for action – finishing the level

Hero's trial – creating a health pickup

Lighting basics

Creating lights

Light component properties

Animating in Unity

Creating clips

Time for action – creating a new clip

Recording keyframes

Time for action – spinning animation

Curves and tangents

Time for action – smoothing the spin

The particle system

Time for action – adding sparkle effects

Pop quiz – basic Unity features

Summary

Movement, Camera Controls, and Collisions

Moving the player

Player setup

Time for action – creating the player capsule

Understanding vectors

Getting player input

Time for action – player locomotion

Camera follow

Time for action – Scripting camera behavior

Working with Unity physics

Rigidbodies in motion

Time for action – accessing the Rigidbody

Time for action – moving the Rigidbody

Colliders and collisions

Time for action – picking up an item

Using Collider triggers

Time for action – creating an enemy

Time for action – capturing trigger events

Hero's trial – all the prefabs!

Physics roundup

Pop quiz – player controls and physics

Summary

Scripting Game Mechanics

Adding jumps

Enter enumerations

Underlying types

Time for action – pressing the spacebar to jump!

Working with layer masks

Time for action – setting object layers

Time for action – one jump at a time

Shooting projectiles

Instantiating objects

Time for action – creating a projectile prefab

Time for action – adding the shooting mechanic

Managing GameObject buildup

Time for action – destroying bullets

The game manager

Tracking player properties

Time for action – creating a game manager

The Get and Set properties

Time for action – adding backing variables

Time for action – updating item collection

Player Polish

Graphical User Interfaces

Time for action – adding UI elements

Win and Loss Conditions

Time for action – winning the game

Using directives and namespaces

Time for action – pausing and restarting

Pop quiz – working with mechanics

Summary

Basic AI and Enemy Behavior

Navigating in Unity

Navigation components

Time for action – setting up the NavMesh

Time for action – setting up enemy agents

Moving enemy agents

Procedural programming

Time for action – referencing the patrol locations

Time for action – moving the enemy

Time for action – patrolling continuously between locations

Enemy game mechanics

Seek and destroy

Time for action – changing the agent's destination

Time for action – lowering player health

Time for action – detecting bullet collisions

Time for action – updating the game manager

Refactoring and keeping it DRY

Time for action – creating a restart method

Hero's trial – refactoring win/lose logic

Pop quiz – AI and navigation

Summary

Section 3: Leveling Up Your C# Code

Revisiting Types, Methods, and Classes

Access Modifier redux

Constant and read-only properties

Using the static keyword

Time for action – creating a static class

Methods Redux

Overloading methods

Time for action – overloading the level restart

Ref parameters

Time for action – tracking player restarts

Out parameters

OOP redux

Interfaces

Time for action – creating a manager interface

Time for action – adopting an interface

Abstract classes

Class extensions

Time for action – extending the string class

Time for action – using an extension method

Namespace Redux

Type aliasing

Pop quiz – leveling up

Summary

Exploring Generics, Delegates, and Beyond

Introducing generics

Generic objects

Time for action – creating a generic collection

Generic methods

Time for action – adding a generic item

Constraining type parameters

Time for action – limiting generic elements

Delegating actions

Basic syntax

Time for action – creating a debug delegate

Delegates as parameter types

Time for action – using a delegate argument

Firing events

Basic syntax

Time for action – creating an event

Handling event subscriptions

Time for action – subscribing to an event

Handling exceptions

Throwing exceptions

Time for action – checking negative scene indexes

Using a try-catch

Time for action – catching restart errors

Design pattern primer

Common game patterns

Pop quiz – intermediate C#

Summary

The Journey Continues

Scratching the surface

Putting the pieces together

Remembering your OOP

Approaching Unity projects

Unity features we didn't cover

Next steps

C# resources

Unity resources

Unity certifications

Hero's trial – putting something out into the world

Summary

Completed Game Files

Bullet behavior

Camera behavior

Enemy behavior

Game behavior

Item behavior

Player behavior

Supplementary Classes

Custom extensions

IManager

Inventory list

Utilities

Pop Quiz Answers

Chapter 1 – Getting to Know Your Environment

Pop quiz – dealing with scripts

Chapter 2 – Introducing the Building Blocks of Programming

Pop quiz – C# building blocks

Chapter 3 – Diving into Variables, Types, and Methods

Pop quiz #1 – variables and types

Pop quiz #2 – understanding methods

Chapter 4 – Using Collections and Controlling Your Code

Pop quiz #1 – If, and, or but

Pop quiz #2 – all about collections

Chapter 5 – Working with Classes, Structs, and OOP

Pop quiz – all things OOP

Chapter 6 – Getting Your Hands Dirty with Unity

Pop quiz – basic Unity features

Chapter 7 – Movement, Camera Controls, and Collisions

Pop quiz – player controls and physics

Chapter 8 – Scripting Game Mechanics

Pop quiz – working with mechanics

Chapter 9 – Basic AI and Enemy Behavior

Pop quiz – AI and navigation

Chapter 10 – Revisiting Types, Methods, and Classes

Pop quiz – leveling up

Chapter 11 – Exploring Generics, Delegates, and Beyond

Pop quiz – intermediate C#

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Unity has become one of the most popular game engines in the world, catering to amateur hobbyists, professional AAA studios, and cinematic production houses. While mainly considered a 3D tool, Unity has a host of dedicated features that support everything from 2D games and virtual reality to post-production and cross-platform publishing.

While developers love its drag-and-drop interface and built-in features, it's the ability to write custom C# scripts for behaviors and game mechanics that really take Unity the extra mile. Learning to write C# code might not be a huge obstacle to a seasoned programmer that already has other languages under his or her belt, but it can be daunting for those of you who have no programming experience. That's where this book comes in, as I'll be taking you through the building blocks of programming and the C# language from scratch, all while building a fun and playable game in Unity.

Who this book is for

This book was written primarily for those of you who don't have any experience with the basic tenants of programming or the C# language. If you're a competent novice or seasoned programmer coming from another language, or even C#, but need to get hands-on with game development in Unity, then this is where you need to be.

What this book covers

Chapter 1, Getting to Know Your Environment, will get you started with the Unity installation process, the editor's main features, and finding documentation for both C# and Unity-specific topics. We'll also go through creating C# scripts from inside Unity and take a look at the Visual Studio application, where all our code editing will take place.

Chapter 2, The Building Blocks of Programming, begins by laying out the atomic-level concepts of programming, giving you an opportunity to relate variables, methods, and classes to situations in everyday life. From there we move on to simple debugging techniques, proper formatting and commenting, and take a look at how Unity turns C# scripts into components.

Chapter 3, Diving into Variables, Types, and Methods, takes a deeper look at variables. This includes C# data types, naming conventions, access modifiers, and everything else you'll need for the foundation of a program. We'll also go over how to write methods, incorporate parameters, and use return types effectively, ending with an overview of standard Unity methods belonging to the MonoBehaviour class.

Chapter 4, Control Flow and Collection Types, introduces the common approaches to making decisions in code, consisting of the if-else and switch statements. From there we move on to working with arrays, lists, and dictionaries, and incorporating iteration statements for looping through collection types. We end the chapter with a look at conditional looping statements and a special C# data type called enumerations.

Chapter 5, Working with Classes, Structs, and OOP, details our first contact with constructing and instantiating class and struct objects in code. We'll go through the basic steps of creating constructors, adding class or struct variables and methods, and the fundamentals of subclassing and inheritance. The chapter will end with a comprehensive explanation of object-oriented programming and how it applies to C#.

Chapter 6, Getting Your Hands Dirty with Unity, will mark our departure from C# syntax into the world of game design, level building, and Unity's featured tools. We'll start by going over the basics of a game design document, then move into blocking out our level geometry and adding lighting and a simple particle system.

Chapter 7, Movement, Camera Controls, and Collisions, will explain different approaches to moving a player object and setting up a third-person camera. We'll discuss incorporating Unity physics for more realistic locomotion effects, as well as how to work with collider components and capture interactions within a scene.

Chapter 8, Scripting Game Mechanics, will introduce the concept of game mechanics and how to effectively implement them. We'll start with a simple jump action, and create a shooting mechanic, and build off the last chapter's code by adding logic to handle item collection.

Chapter 9, Basic AI and Enemy Behavior, starts with a brief overview of artificial intelligence in games and the concepts we will be applying to Hero Born. Topics covered in this chapter will include navigation in Unity using the level geometry and a navigation mesh, smart agents, and automated enemy movement.

Chapter 10, Revisiting Types, Methods, and Classes, takes a more in-depth look at data types, intermediate method features, and additional behaviors that can be used for more complex classes. This chapter will give you a deeper understanding of the versatility and breadth of the C# language.

Chapter 11, Exploring Generics, Delegates, and Beyond, will detail some of the more intermediate features of the C# language and how to apply them in practical, real-world scenarios. We'll start with an overview of generic programming and progress to concepts such as delegation, events, and exception handling. The chapter will end with a brief discussion of common design patterns and set you up for further study.

Chapter 12, The Journey Continues, reviews the main topics you've learned throughout the book and leaves you with resources for further study in both C# and Unity. Included in these resources will be online reading material, certification information, and a host of my favorite video tutorial channels.

Appendix A, Completed Game Files, contains all the necessary C# scripts that make up Hero Born.

Appendix B, Supplementary Classes, contains the intermediate code from Chapters 10, Revisiting Types, Methods, and Classes and Chapter 11, Exploring Generics, Delegates, and Beyond, that don't have any direct impact on the game mechanics of Hero Born.

Appendix C, Pop Quiz Answers, contains the answers to each chapter quiz presented throughout the book.

To get the most out of this book

The only thing you need to get the most from your upcoming C# and Unity adventure is a curious mind and a will to learn. Having said that, doing all the Time for Action and Heroes Trial sections is a must if you hope to cement the knowledge you're learning, as well as completing the chapter quizzes. Lastly, revisiting topics and entire chapters to refresh or solidify your understanding before moving on is always a good idea. There's no sense building a house on an unstable foundation.

Downloading the Example Code Files

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

Log in or register at

www.packt.com

.

Select the SUPPORT tab.

Click on Code Downloads & Errata.

Enter the name of the book in the Search box and follow the onscreen instructions.

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

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

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

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

Downloading the Color Images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book, which you can download here: https://www.packtpub.com/sites/default/files/downloads/9781789532050_ColorImages.pdf.

Conventions Used

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

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Optionally, anelsekeyword with its own pair of curly brackets and code block"

A block of code is set as follows:

publicintfirstName= "Bilbo";

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

accessModifier

returnType UniqueName(

parameterType parameterName

) { method body }

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Choose Create, and select C# Script"

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

Sections

In this book, you will find several headings that appear frequently (Time for action, What just happened?, Pop quiz, and Hero's trial).

To give clear instructions on how to complete a procedure or task, we use these sections as follows:

Time for Action

Step 1

Step 2

Step 3

Extra explanations are often required to break down instructions, so they are followed with:

What just happened?

This heading explains the working of tasks or instructions that you have just completed. You will also find some other learning aids in the book, including:

Pop Quiz – Heading

These are short multiple-choice questions intended to help you test your own understanding.

Hero's Trial – Heading

These practical challenges give you ideas for experimenting with what you have learned.

Get in Touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

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

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

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

Reviews

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

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

Section 1: Programming Foundations and C#

This section will introduce you to the Unity development environment, the fundamentals of programming, and the C# language from the ground up. By the end of this section, you'll know your way around Unity and have the foundational knowledge necessary to start creating a simple game.

The following chapters will be covered in this section:

Chapter 1

,

Getting to Know Your Environment

Chapter 2

,

The Building Blocks of Programming

Chapter 3

,

Diving into Variables, Types, and Methods

Chapter 4

,

Control Flow and Collection Types

Chapter 5

,

Working with Classes, Structs, and OOP

Getting to Know your Environment

Pop culture has taught us that computer programmers are usually outsiders, lone wolves, or geeky hackers who possess extraordinary mental gifts for algorithmic thought, little social IQ, and the odd anarchic bent. While this is definitely not the case, in reality, there is something to the idea that learning to code fundamentally changes the way you look at the world. The good news is that your naturally curious mind will quickly adapt to this new way of thinking, and maybe even come to enjoy it.

You already use analytical skills in your everyday life that translate to programming—you're just missing the right language and syntax to map those life skills into code. You know your age, right? That's a variable. When you cross the street, I presume you look left, right, then left again like the rest of us. That's evaluating different conditions or what we call control flow. When you look at a can of pop, you instinctively identify that it has properties, such as shape, weight, and contents. That's a class object. You get the idea.

We're going to begin our adventure into C# programming by covering the following topics:

Basic prerequisites

Starting out with Unity

Using C# with Unity

Working with the Visual Studio editor

Accessing documentation and resources

Some basic prerequisites

Sometimes it's easier to start with what a thing isn't, rather than what it is. The main goal of this book isn't to learn the vast ins and outs of Unity or all of game development. By necessity, we'll cover these topics at a basic level, and in more detail in Chapter 6, Getting Your Hands Dirty with Unity, but their purpose is to provide a fun, accessible way for us to learn the C# programming language from the ground up.

Since this book is aimed at complete beginners to programming, if you have no previous experience with either C# or Unity, you're in the right place! If you've had some experience with the Unity editor but not with programming, guess what? This is still the place to be. Even if you've dabbled in a bit of C# mixed with Unity, but want to explore some more intermediate or advanced topics, the later chapters can provide you with what you're looking for.

If you're an experienced programmer in other languages, feel free to skip the beginner theory and dive right into the parts you're interested in.

Starting out with Unity 2019

Head over to https://store.unity.com/ and you'll see a few options. Don't get overwhelmed—you can get Unity completely free by selecting the personal option on the right. The other paid options offer more advanced functionality and services, but you can check these out on your own down the road:

After selecting the personal plan, you'll end up on the download screen; accept the terms and conditions and hit Download Installer for Mac OS X:

If you're using a Windows machine, select the Choose Windows link located underneath the installer button, accept the terms and conditions, and you're good to go!

You can also download and manage different versions of Unity through the Unity Hub application, which can be also be downloaded from this screen.

When the download is complete, open up the package (by double-clicking it) and follow the installation instructions. When you get the green light, go ahead and fire up Unity!

All of the examples and screenshots for this book were created and captured using Unity 2018.3.8f1 and verified with version 2019.2.0a7. If you're using a newer version, things might look slightly different in the editor, but following along won't be a problem.

Creating a new project

The first thing you'll see whenUnityfinishes thinking aboutopeningis the dashboard. If you have a Unity account, go ahead andSign in. If not, you can either create one or hitSkipat the bottom of the screen.

Now, let's set up a new project by selecting the New tab at the top right and setting the following fields:

Project Name

: I'll be calling mine

Hero Born

Location

:Wherever you'd like the project to be saved

Template

: Make sure this is set to

3D

and hit

Create Project

:

Navigating the editor

When the new project finishes initializing, you'll see the glorious Unity editor! I've marked the important tabs (or panels, if you prefer) in the following screenshot, which we can break down as follows:

The

Toolbar

is the topmost part of the Unity editor. From here, you can manipulate objects (far-left button group), and play and pause the game (center buttons). The rightmost button group contains Unity Services, layer masks, and layout scheme features that we won't be using in this book.

The

Hierarchy Window

shows every item currently in the game scene. In the starter project, this is just the default camera and directional light, but when we create our prototype environment, this window will start to get filled in.

The

Game

and

Scene Views

are the most visual aspects of the editor. Think of the

Scene View

as your stage, where you can move and arrange 2D and 3D objects. When you hit

Play

, the

Game View

will take over, rendering the

Scene

and any programmed interactions.

The

Inspector

Window is your one-stop-shop for viewing and editing the properties of your objects. In the preceding screenshot, you can see that the

Main Camera

has several parts (Unity calls them components) displayed – all of them are accessible from here.

The

Project

window holds every asset that's currently in your project. Think of this as a representation of your project's folders and files.

The

Console

is where any output we want our scripts to print will show up. From here on out, if we talk about the console or debug output, this panel is where it will be displayed.

You can find more in-depth breakdowns of each window's functionality in the Unity docs at https://docs.unity3d.com/Manual/UsingTheEditor.html.

I know that was a lot to process if you're new to Unity, but rest assured that any instructions going forward will always reference the necessary steps. I won't leave you hanging, wondering what button to push. With that out of the way, let's get a jump on creating some actual C# scripts.

Using C# with Unity

Going forward, it's important to think of Unity and C# as symbiotic entities. Unity is the engine where you will create scripts and eventually run them, but the actual programming will take place in another program, called Visual Studio. Don't sweat that right now—we'll get to that in a moment.

Working with C# scripts

Even though we haven't covered any basic programming concepts yet, we still need to know how to create a C# script in Unity.

There are several ways to create C# scripts in the editor:

From the menu bar, navigate to

Assets

|

Create

|

C# Script

In the

Project

tab, select

Create

|

C# Script

Right-clickin the

Project

tab (on the right-hand side) and select

Create

|

C#

Script

from the popup menu

Going forward, whenever you're instructed to create a C# script, please use whichever method you prefer.
Resources and objects other than C# scripts can be created in the editor using the preceding methods. I'm not going to call out each of these variations every time we create something new, so just keep the options in the back of your mind.

Time for action – creating a C# script

For the sake of organization, we're going to store our various assets and scripts inside their own clearly marked folders. This isn't just a Unity-related task—it's something you should always do (your coworkers will thank you, I promise):

Click

Create

|

Folder

(or whichever method you like best) from the

Project

tab and name it

Scripts

.

Double-click on the

S

cripts

folder and create a new C# script. By default, the script will be named

NewBehaviourScript

, so immediately rename it to

LearningCurve

.

What just happened?

We've just created a subfolder named Scripts, which is pictured in the following screenshot. Inside that parent folder, we've created a C# script named LearningCurve.cs (the csfile type stands for C-Sharp, in case you were wondering), which is now saved as part of our Hero Born project assets:

Introducing the Visual Studio editor

While Unity can create and store C# scripts, they need to be edited using an application calledVisual Studio. A copy of Visual Studio comes pre-packaged with Unity and will open up automatically when you double-click any C# script from inside the editor.

Time for action – opening a C# file

Unity will synchronize with Visual Studio the first time you open a file. The simplest way to do this is to select a script from the Project tab:

In Unity's

Project

tab, double-click on

LearningCurve.cs

and watch it open up in Visual Studio: