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

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

Harrison Ferrone

0,0
52,79 €

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

Mehr erfahren.
Beschreibung

Over the years, the Learning C# by Developing Games with Unity series has established itself as a popular choice for getting up to speed with C#, a powerful and versatile programming language that can be applied in a wide array of application areas. This book presents a clear path for learning C# programming from the ground up without complex jargon or unclear programming logic, all while building a simple game with Unity.
This fifth edition has been updated to introduce modern C# features with the latest version of the Unity game engine, and a new chapter has been added on intermediate collection types. Starting with the basics of software programming and the C# language, you’ll learn the core concepts of programming in C#, including variables, classes, and object-oriented programming. Once you’ve got to grips with C# programming, you’ll enter the world of Unity game development and discover how you can create C# scripts for simple game mechanics. Throughout the book, you’ll gain hands-on experience with programming best practices to help you take your Unity and C# skills to the next level.
By the end of this book, you’ll be able to leverage the C# language to build your own real-world Unity game development projects.

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

EPUB

Seitenzahl: 375

Veröffentlichungsjahr: 2020

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 2020Fifth 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 2020Fifth 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 RamchandaniAcquisition Editor: Ashitosh GuptaContent Development Editor: Akhil NairSenior Editor: Hayden EdwardsTechnical Editor: Deepesh PatelCopy Editor: Safis EditingProject Coordinator: Kinjal BariProofreader: Safis EditingIndexer: Pratik ShirodkarProduction 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 [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 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

Title Page

Copyright and Credits

Learning C# by Developing Games with Unity 2020 Fifth Edition

Dedication

About Packt

Why subscribe?

Contributors

About the author

About the reviewers

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

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Getting to Know Your Environment

Technical requirements

Getting started with Unity 2020

Using macOS 

Creating a new project

Navigating the editor

Using C# with Unity 

Working with C# scripts

Introducing the Visual Studio editor

Time for action – opening a C# file

Beware of naming mismatches

Syncing C# files

Exploring the 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

Summary

Pop quiz – dealing with scripts

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

Understanding methods

Methods drive actions

Methods are placeholders too

Time for action – creating a simple method

Introducing classes

A common Unity class

Classes are blueprints

Working with comments

Practical backslashes

Multi-line comments

Time for action – adding comments

Putting the building blocks together

Scripts become components

A helping hand from MonoBehavior

Hero's trial – MonoBehavior in the Scripting API

Communication among classes

Summary

Pop quiz – C# building blocks

Diving into Variables, Types, and Methods

Writing proper C#

Debugging your code

Declaring variables

Type and value declarations

Type-only declarations

Using 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

Understanding variable scope

Introducing operators

Arithmetic and assignments

Time for action – executing incorrect type operations

Defining methods

Basic syntax

Modifiers and parameters

Time for action – defining a simple method

Naming conventions

Methods are logic detours

Specifying parameters

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

Dissecting common Unity methods

The Start method

The Update method

Summary

Pop quiz – variables and methods

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

foreach loops

Looping through key-value pairs

Hero's trial – finding affordable items

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

Declaring structs

Basic syntax

Time for action – creating a weapon struct

Understanding reference and value types

Reference types

Time for action – creating a new hero

Value types

Time for action – copying weapons

Integrating 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

Time for action – finding components on different objects

Drag and drop

Time for action – assigning variables in Unity

Summary

Pop quiz – all things OOP

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

Summary

Pop quiz – basic Unity features

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

Adding a following Camera

Time for action – scripting camera behavior

Working with Unity physics

Rigidbody components in motion

Time for action – accessing the Rigidbody component

Time for action – moving the Rigidbody component

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

Summary

Pop quiz – player controls and physics

Scripting Game Mechanics

Adding jumps

Introducing 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

Creating a 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

Adding player polish

Graphical UI

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 

Summary

Pop quiz – working with mechanics

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

Summary

Pop quiz – AI and navigation

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

Summary

Pop quiz – leveling up

Introducing Stacks, Queues, and HashSets

Introducing stacks

Basic syntax

Time for action – storing collected items

Popping and peeking

Time for action – the last item collected

Common methods

Working with queues

Basic syntax

Adding, removing, and peeking

Common methods

Using HashSets

Basic syntax

Performing operations

Summary

Pop quiz – intermediate collections

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 try-catch

Time for action – catching restart errors

Design pattern primer

Common game patterns

Summary

Pop quiz – intermediate C#

The Journey Continues

Scratching the surface

Remembering your object-oriented programming

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

Pop Quiz Answers

Chapter 1 – Getting to Know Your Environment

Pop quiz – dealing with scripts

Chapter 2 – 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 – Introducing Stacks, Queues, and HashSets

Pop quiz – intermediate collections

Chapter 12 – Exploring Generics, Delegates, and Beyond

Pop quiz – intermediate C#

Other Books You May Enjoy

Leave a review - let other readers know what you think

Getting to Know Your Environment

Pop culture has taught us that computer programmers are often 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 not the case, 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 may 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 down the road in both directions before stepping off the curb like the rest of us. That's evaluating different conditions, or what we call control flow in programming parlance. When you look at a can of pop, you instinctively identify that it has certain properties such as shape, weight, and contents. That's a class object! You get the idea.

With all that real-world experience at your fingertips, you're more than ready to cross over into the realm of programming. You'll need to know how to set up your development environment, work with the applications involved, and know exactly where to go when you need help. To that end, we're going to begin our adventure delving into C# by covering the following topics:

Getting started with Unity

Working with Visual Studio

Using C# with Unity

Exploring the documentation

Let's get started!

Technical requirements

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 the Unity game engine or all of game development. By necessity, we'll cover these topics at a basic level here at the beginning of our journey, and in more detail in Chapter 6, Getting Your Hands Dirty with Unity. However, these topics are simply 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 of this book 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, or stick around and refresh your fundamentals.

Getting started with Unity 2020

If you don’t have Unity installed already, or are running an earlier version, you'll need to do a little setup. Follow these steps:

Head over to 

https://www.unity.com/

.

Select

Get Started

 (shown in the following screenshot), which will take you to the Unity store page:

If the Unity home page looks different for you than what you can see in the preceding screenshot, you can go directly to https://store.unity.com.

Don't feel overwhelmed by this – you can get Unity completely free!

Click the 

Individual

 tab and select the

Personal

option on the left. The other paid options offer more advanced functionality and services subscribers, but you can check these out on your own:

After selecting the personal plan, you'll be asked if you're a first-time or returning user.

Select 

Start here

under

First-time Users

:

 

Select 

Agree

 

and

 

download

 to get your copy of Unity Hub:

Once the download is complete, follow these steps: 

Open up the package (by double-clicking it).

Accept the user agreement.

Follow the installation instructions. When you get the green light, go ahead and fire up the Unity Hub application! You'll see the following screen:

The newest version of Unity Hub has a wizard or getting started path when you first open the application. If you'd like to follow that, feel free. The following steps show you how to start a new project without any help from the application since that's only available on the first launch.

Wit

h Unity Hub open, s

witch to the 

Installs

 

tab from the left-hand menu and select 

ADD

:

At the time of writing, Unity 2020 is still in its Alpha phase, but you should be able to select a 2020 version from the Latest Official Releases list:

You won't need any specific platform modules to follow along with future examples, so go ahead and leave this as-is. If you do want to add them at any time, you can click the More button (three-dot icon) at the upper right of any version in the Installs window:

When the installation is complete, you'll see a new version in your Installs panel, as follows:

You can find additional information and resources about the Unity Hub application at https://docs.unity3d.com/Manual/GettingStartedInstallingHub.html.

There's always a chance of something going wrong, so be sure to check the following section if you're using macOS Catalina or higher. 

Using macOS 

If you're working on a Mac with OS Catalina or later, there is a known issue with using Unity Hub 2.2.2 (and earlier versions) to install Unity with the preceding steps. If that's the case for you, take a deep breath and go to the Unity download archive and grab the version you need (https://unity3d.com/get-unity/download/archive). Remember to use the Downloads (Mac) option instead of the Unity Hub download:

If you're working on Windows and run into similar install issues, the steps we just took will also work just fine.

The download is a normal application installer since it's a .dmg file. Open it up, follow the instructions, and you'll be ready to go in no time!

All of the examples and screenshots for this book were created and captured using Unity 2020.1.0a20. If you're using a newer version, things might look slightly different in the Unity editor, but this shouldn't affect you following along.

Now that Unity Hub and Unity 2020 are installed, it's time to create a new project!

Creating a new project

Launch the Unity Hub application to start a new project. If you have a Unity account, go ahead and sign-in; if not, you can either create one or hit Skip at the bottom of the screen.

Now, let's set up a new project by selecting the arrow icon next to the NEW tab at the top-right:

Choose your 2020 version and set the following fields:

Project Name

: I'll be calling mine 

Hero Born

.

Location

: Wherever you'd like the project to be saved.

Template

: The project will default to 

3D

, so hit 

CREATE

:

With the project created, you're all set to explore the Unity interface.

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:

This is a lot to take in, so we'lllook at each of these panels in more detail:

The 

Toolbar

 panel 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, which 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 the 

Play 

button, the 

Game

 

view

 will take over, rendering the 

Scene

 view and any programmed interactions.

The 

Inspector

 

window is your one-stop-shop for viewing and editing the properties of your objects. If you select the 

Main Camera

 component, you'll see several parts (Unity calls them components) are displayed – all of which 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

 panel 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 or wondering what button to push. With that out of the way, let's start 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'll create scripts and eventually run them, but the actual programming takes place in another program called Visual Studio. Don't worry about 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, they won't have a home until we know how to create an actual C# script in Unity. 

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

Select 

Assets

 

Create

 |

 

C# Script

.

In the 

Project

 tab, select 

Create

 |

 

C# Script

.

Right-click in the 

Project

 tab (on the right-hand side) and select

 

Create

 | 

C#

 

Script

 

from the pop-up menu.

Select a GameObject in the

Hierarchy

window and click

Add Component

|

New Script

.

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.

For the sake of organization, we're going to store our various assets and scripts inside their marked folders. This isn't just a Unity-related task – it's something you should always do, and 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 

Scripts

 

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

NewBehaviourScript

, but you'll see the filename highlighted, so you have the option to immediately rename it. Type in 

LearningCurve

 and hit

Enter

:

We've just created a subfolder named Scripts, as shown in the preceding screenshot. Inside that parent folder, we've created a C# script named LearningCurve.cs (the.cs file type stands for C-Sharp, in case you were wondering), which is now saved as part of our Hero Born project assets. All that's left to do is open it up in Visual Studio!

Introducing the Visual Studio editor

While Unity can create and store C# scripts, they need to be edited using Visual Studio. A copy of Visual Studio comes pre-packaged with Unity and will open it 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 by selecting the script from the Projects tab.

Double-click on LearningCurve.cs, as follows:

This will open up the C# file in Visual Studio:

If the file opens up in another default application, follow these steps:

Select 

Unity

|

Preferences

 

from the top menu and choose 

External Tools

 

in the left-hand panel.

Change the 

External Script Editor

 

to

Visual Studio

, as shown in the following screenshot:

You'll see a folder structure on the left-hand side of the interface that mirrors the one in Unity, which you can access like any other. On the right-hand side is the actual code editor where the magic happens. There are far more features to the Visual Studio application, but this is all we need to get the programmatic ball rolling.

The Visual Studio interface is different for Windows and Mac environments, but the code we'll be using throughout this book will work equally well with both. All the screenshots in this book have been taken in a Mac environment, so if things look different on your computer, there's no need to worry.

Beware of naming mismatches

One common pitfall that trips up new programmers is file naming – more specifically, naming mismatches – which we can illustrate using line 5 from the previous screenshot of the C# file in Visual Studio:

public class LearningCurve : MonoBehaviour

The LearningCurve class name is the same as the LearningCurve.cs filename. This is an essential requirement. It's OK if you don't know what a class is quite yet. The important thing to remember is that, in Unity, the filename and the class name need to be the same. If you're using C# outside of Unity, the filename and class name don't have to match.

When you create a C# script file in Unity, the filename in the Project tab is already in Edit mode, ready to be renamed. It's a good habit to rename it then and there. If you rename the script later, the filename and the class name won't match. The filename would change, but line five would be as follows:

public class NewBehaviourScript : MonoBehaviour

If you accidentally do this, it's not the end of the world. All you need to do is go into Visual Studio and change NewBehaviourScript to the name of your C# script.

Syncing C# files

As part of their symbiotic relationship, Unity and Visual Studio keep in touch with each other to synchronize their content. This means that if you add, delete, or change a script file in one application, the other application will see the changes automatically.

So, what happens when Murphy's Law strikes and syncing just doesn't seem to be working correctly? If you run into this situation, take a deep breath, select the troublesome script, right-click, and select Refresh. 

You now have the basics of script creation under your belt, so it's time we talk about finding and efficiently using helpful resources.

Exploring the documentation

The last topic we'll touch on in this first foray into Unity and C# scripts is documentation. Not sexy, I know, but it's important to form good habits early when dealing with new programming languages or development environments.

Accessing Unity's documentation

Once you start writing scripts in earnest, you'll be using Unity's documentation quite often, so it's beneficial to know how to access it early on. The Reference Manual will give you an overview of a component or topic, while specific programming examples can be found in the Scripting Reference.

Time for action – opening the Reference Manual

Every GameObject (an item in the Hierarchy window) in a Scene has a Transform component that controls its Position,Rotation, andScale. To keep things simple, we'll just look up the camera's Transform component in the Reference Manual:

In the 

Hierarchy

 tab, select the 

Main Camera

 object.

Move over to the 

Inspector

 tab and click on the information icon (question mark) at the top-right of the 

Transform

 component:

You'll see a web browser open on the Transform page of the Reference Manual. All the components in Unity have this feature, so if you ever want to know more about how something works, you know what to do:

Time for action – using the Scripting Reference

So, we've got the Reference Manual open, but what if we wanted concrete coding examples related to the Transform component? It's pretty simple – all we need to do is ask the Scripting Reference.

Click on Scripting API, or the Switch to Scripting link underneath the component or class name (Transform, in this case).

By doing this, the Reference Manual automatically switches to the Scripting Reference for the Transform component:

The Scripting Reference is a large document because it has to be. However, this doesn't mean you have to memorize it or even be familiar with all of its information to start writing scripts. As the name suggests, it's a reference, not a test. 

If you find yourself lost in the documentation, or just out of ideas regarding where to look, you can also find solutions within the rich Unity development community in the following places:

Unity ForumsUnity AnswersUnity Discord

On the other side of things, you'll need to know where to find resources on any C# question, which we'll cover next. 

Locating C# resources

Now that we've got our Unity resources taken care of, let's take a look at some of Microsoft's C# documents at https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/index.