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

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

Harrison Ferrone

0,0
45,59 €

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

Mehr erfahren.
Beschreibung

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 with a wide array of applications in various domains. This bestselling franchise presents a clear path for learning C# programming from the ground up through the world of Unity game development.

This sixth edition has been updated to introduce modern C# features with Unity 2021. A new chapter has also been added that covers reading and writing binary data from files, which will help you become proficient in handling errors and asynchronous operations.

The book acquaints you with the core concepts of programming in C#, including variables, classes, and object-oriented programming. You will explore the fundamentals of Unity game development, including game design, lighting basics, player movement, camera controls, and collisions. You will write C# scripts for simple game mechanics, perform procedural programming, and add complexity to your games by introducing smart enemies and damage-causing projectiles.

By the end of the book, you will have developed the skills to become proficient in C# programming and built a playable game prototype with the Unity game engine.

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

EPUB
MOBI

Seitenzahl: 461

Veröffentlichungsjahr: 2021

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 2021

Sixth Edition

Kickstart your C# programming and Unity journey by building 3D games from scratch

Harrison Ferrone

BIRMINGHAM—MUMBAI

Learning C# by Developing Games with Unity 2021

Sixth Edition

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

Producer: Caitlin Meadows, Manish Nainani

Acquisition Editor – Peer Reviews: Saby Dsilva

Project Editor: Namrata Katare

Content Development Editor: Edward Doxey

Copy Editor: Safis Editing

Technical Editor: Aniket Shetty

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Presentation Designer: Ganesh Bhadwalkar

First published: September 2013

Second edition: March 2016

Third edition: December 2017

Fourth edition: March 2019

Fifth edition: August 2020

Sixth edition: October 2021

Production reference: 3141022

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80181-394-5

www.packt.com

"If people reach perfection, they vanish, you know."

- T.H. White, The Once and Future King

Contributors

About the author

Harrison Ferrone was born in Chicago, Illinois and was raised all over. He's worked at Microsoft, PricewaterhouseCoopers, and a handful of small start-ups, but 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, these are stored in a basement somewhere.

After a few years as a full-time iOS and Unity developer, he fell into a teaching career and never looked back. Throughout all of this, he's bought many books, been owned by several cats, worked abroad, and continually wondered why Neuromancer isn't on more course syllabi.

Completing this book wouldn't have been possible without loving support from Kelsey, my wife and partner in crime on this journey.

About the reviewers

Simon Jackson is a long-time software engineer and architect with many years of Unity game development experience, as well as the author of several Unity game development titles. He loves to both create Unity projects as well as lend a hand to help educate others, whether it's via a blog, vlog, user group, or major speaking event.

His primary focus at the moment is with the XRTK (Mixed Reality Toolkit) project, which is aimed at building a cross-platform mixed reality framework to enable both VR and AR developers to build efficient solutions in Unity and then build/distribute them to as many platforms as possible.

Joshua Steinhauer is a game developer by day, indie developer by night. Having picked up programming at a young age, Joshua has stuck to his passion ever since, and has shown no signs of stopping. He loves building tools to speed up development and help make others' jobs easier.

His favorite games are The Elder Scrolls III: Morrowind and Fallout: New Vegas, and he has spent the past four years developing an open world RPG in Unity and leading a team to make it possible. His dream is to start his own game studio!

JOIN us on Discord!

Read this book alongside other users, Unity/C# experts, and Harrison Ferrone. Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions and much more.

Join Now!

https://packt.link/csharpunity2021

Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Get in touch

Getting to Know Your Environment

Technical requirements

Getting started with Unity 2021

Using macOS

Creating a new project

Navigating the editor

Using C# with Unity

Working with C# scripts

Introducing the Visual Studio editor

Opening a C# file

Beware of naming mismatches

Syncing C# files

Exploring the documentation

Accessing Unity's documentation

Locating C# resources

Summary

Pop quiz – dealing with scripts

The Building Blocks of Programming

Defining variables

Names are important

Variables act as placeholders

Understanding methods

Methods drive actions

Methods are placeholders too

Introducing classes

A common Unity class

Classes are blueprints

Communication among classes

Working with comments

Single-line comments

Multi-line comments

Adding comments

Putting the building blocks together

Scripts become components

A helping hand from MonoBehaviour

Hero's trial – MonoBehaviour in the Scripting API

Summary

Pop quiz – C# building blocks

Diving into Variables, Types, and Methods

Writing proper C#

Debugging your code

Understanding variables

Declaring variables

Type and value declarations

Type-only declarations

Using access modifiers

Working with types

Common built-in types

Type conversions

Inferred declarations

Custom types

Naming variables

Understanding variable scope

Introducing operators

Arithmetic and assignments

Defining methods

Declaring methods

Naming conventions

Methods as logic detours

Specifying parameters

Specifying return values

Using 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

Using the NOT operator

Nesting statements

Evaluating multiple conditions

The switch statement

Pattern matching

Fall-through cases

Pop quiz 1 – if, and, or but

Collections at a glance

Arrays

Indexing and subscripts

Range exceptions

Lists

Accessing and modifying lists

Dictionaries

Working with dictionary pairs

Pop quiz 2 – all about collections

Iteration statements

for loops

foreach loops

Looping through key-value pairs

while loops

To infinity and beyond

Summary

Working with Classes, Structs, and OOP

Introducing OOP

Defining classes

Instantiating class objects

Adding class fields

Using constructors

Declaring class methods

Declaring structs

Understanding reference and value types

Reference types

Value types

Integrating the object-oriented mindset

Encapsulation

Inheritance

Base constructors

Composition

Polymorphism

Applying OOP in Unity

Objects are a class act

Accessing components

Accessing components in code

Drag and drop

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

Thinking in 3D

Materials

White-boxing

Editor tools

Hero's trial – putting up drywall

Keeping the hierarchy clean

Working with Prefabs

Lighting basics

Creating lights

Light component properties

Animating in Unity

Creating animations in code

Creating animations in the Unity Animation window

Recording keyframes

Curves and tangents

Summary

Pop quiz – basic Unity features

Movement, Camera Controls, and Collisions

Managing player movement

Moving the player with the Transform component

Understanding vectors

Getting player input

Moving the player

Scripting camera behavior

Working with the Unity physics system

Rigidbody components in motion

Colliders and collisions

Picking up an item

Using Collider triggers

Creating an enemy

Hero's trial – all the Prefabs!

Physics roundup

Summary

Pop quiz – player controls and physics

Scripting Game Mechanics

Adding jumps

Introducing enumerations

Underlying types

Working with layer masks

Shooting projectiles

Instantiating objects

Adding the shooting mechanic

Managing object build-up

Creating a game manager

Tracking player properties

The get and set properties

Updating item collection

Creating a GUI

Displaying player stats

Win and loss conditions

Pausing and restarting the game with using directives and namespaces

Summary

Pop quiz – working with mechanics

Basic AI and Enemy Behavior

Navigating 3D space in Unity

Navigation components

Setting up enemy agents

Moving enemy agents

Procedural programming

Referencing the patrol locations

Moving the enemy

Enemy game mechanics

Seek and destroy: changing the agent's destination

Lowering player health

Detecting bullet collisions

Updating the game manager

Refactoring and keeping it DRY

Summary

Pop quiz – AI and navigation

Revisiting Types, Methods, and Classes

Access modifiers

Constant and read-only properties

Using the static keyword

Revisiting methods

Overloading methods

ref parameters

out parameters

Intermediate OOP

Interfaces

Abstract classes

Class extensions

Namespace conflicts and type aliasing

Summary

Pop quiz – leveling up

Introducing Stacks, Queues, and HashSets

Introducing stacks

Popping and peeking

Common methods

Working with queues

Adding, removing, and peeking

Common methods

Using HashSets

Performing operations

Intermediate collections roundup

Summary

Pop quiz – intermediate collections

Saving, Loading, and Serializing Data

Introducing data formats

Breaking down XML

Breaking down JSON

Understanding the filesystem

Working with asset paths

Creating and deleting directories

Creating, updating, and deleting files

Working with streams

Managing your Stream resources

Using a StreamWriter and StreamReader

Creating an XMLWriter

Automatically closing streams

Serializing data

Serializing and deserializing XML

Serializing and deserializing JSON

Data roundup

Summary

Pop quiz – data management

Exploring Generics, Delegates, and Beyond

Introducing generics

Generic objects

Generic methods

Constraint type parameters

Adding generics to Unity objects

Delegating actions

Creating a debug delegate

Delegates as parameter types

Firing events

Creating and invoking events

Handling event subscriptions

Cleaning up event subscriptions

Handling exceptions

Throwing exceptions

Using try-catch

Summary

Pop quiz – intermediate C#

The Journey Continues

Diving deeper

Remembering your object-oriented programming

Design patterns primer

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

Other Books You May Enjoy

Index

Landmarks

Cover

Index

Share your thoughts

Once you've read Learning C# by Developing Games with Unity 2021, Sixth Edition, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781801813945

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

1

Getting to Know Your Environment

Pop culture often markets computer programmers as outsiders, lone wolves, or geeky hackers. People possessing 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 your naturally curious mind already wants to see these kinds of patterns in the world, and you may even come to enjoy this new way of thinking.

From the moment your eyes snap open in the morning to the last glimpse of your ceiling fan before you go to sleep, you're unconsciously using analytical skills 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, better known as control flow in programming terminology. When you look at a can of pop, you instinctively identify that it has certain properties like 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. To kick off your journey, 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 those ends, we're going to begin by delving into the following C# topics:

Getting started with Unity 2021Using C# with UnityExploring 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 goal of this book isn't to teach you everything there is to know about the Unity game engine or game development. By necessity, we'll cover these topics at a basic level at the beginning of our journey, and in more detail in Chapter 6, Getting Your Hands Dirty with Unity. However, these topics are included to provide a fun, accessible way 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.

In addition to running Unity 2021, you'll also be using C# 8.0 and Visual Studio to write your game code.

Getting started with Unity 2021

If you don't have Unity installed, or are running an earlier version, follow these steps to set up your environment:

Head over to https://www.unity.com/.Select Get started (shown in the following screenshot):

Figure 1.1: Unity homepage

This will take you to the Unity store page. Don't feel overwhelmed by this—you can get Unity completely for free!

If the Unity homepage looks different for you than what you can see in Figure 1.1, you can go directly to https://store.unity.com.

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

Figure 1.2: Unity plans and pricing

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:

Figure 1.3: Start creating with the Unity portal

Select Agree and download to get your copy of Unity Hub:

Figure 1.4: Unity terms and conditions

Once the download is complete, follow these steps:

Open up the installer (by double-clicking it)Accept the user agreementFollow the installation instructions

When you get the green light, go ahead and fire up the Unity Hub application!

The newest version of Unity Hub will offer an install wizard 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:

Select Skip Install Wizard in the lower left, then confirm Skip Wizard:

Figure 1.5: Install wizard

Switch to the Installs tab from the left-hand menu, and select ADD to choose your Unity version:

Figure 1.6: Unity Hub Installs panel

Select your desired version of Unity, then click NEXT. At the time of writing, Unity 2021 is still in pre-release, but you should be able to select a 2021 version from the Official Releases list by the time you're reading this:

Figure 1.7: Add Unity Version pop-up window

You'll then be given the option to add various modules to your installation. Make sure the Visual Studio module is selected and click NEXT:

Figure 1.8: Adding install modules

If you want to add any modules later, 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:

Figure 1.9: Installs tab with Unity versions

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 later, which has been known to throw up issues.

Using macOS

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

Figure 1.10: Unity download archive

If you're working on Windows and run into similar install issues, downloading an archived copy of Unity 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!

Figure 1.11: Successful Unity installation from the download manager

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

Now that Unity Hub and Unity 2021 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 button in the top right corner:

Figure 1.12: Unity Hub Projects panel

Choose your 2021 version and set the following fields:

Templates: The project will default to 3DProject Name: I'll be calling mine Hero BornLocation: Wherever you'd like the project to be saved

Once the settings have been configured, hit CREATE:

Figure 1.13: Unity Hub with new project configuration popup

With the project created, you're all set to explore the Unity interface! You can re-open your project anytime from the Projects panel in Unity Hub.

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:

Figure 1.14: Unity interface

This is a lot to take in, so we'll look 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, LayerMasks, and layout scheme features, which we won't be using in this book because they don't apply to learning C#.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 windows are the most visual aspects of the editor. Think of the Scenewindow as your stage, where you can move and arrange 2D and 3D objects. When you hit the Play button, the Game window 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 objects in the scene. If you select the Main CameraGameObject in the Hierarchy, 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 window 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.

If any of these windows get closed by accident, you can re-open them anytime from Unity | Window | General. You can find more in-depth breakdowns of each window's functionality in the Unity docs at https://docs.unity3d.com/Manual/UsingTheEditor.html.

Before continuing, it's important that Visual Studio is set up as the script editor for your project. Go to the Unity menu | Preferences | External Tools and check that External Script Editor is set to Visual Studio for Mac or Windows:

Figure 1.15: Changing the External Script Editor to Visual Studio

As a final tip, if you want to switch between light and dark modes, go to the Unity menu | Preferences | General and change the Editor Theme:

Figure 1.16: Unity general preferences panel

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 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 game objects, 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. A C# script is a special kind of C# file in which you'll write C# code. These scripts can be used in Unity to do virtually anything, from responding to player input to creating game mechanics.

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

Select Assets | Create | C# ScriptRight under the Project tab, select the + icon and choose C# ScriptRight-click on the Assets folder in the Project tab and select Create | C# Script from the pop-up menuSelect any 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):

From the Project tab, select + | Folder (or whichever method you like best—in Figure 1.17 we've selected Assets | Create | Folder) and name it Scripts:

Figure 1.17: Creating a C# script

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:

Figure 1.18: Project window with the Scripts folder selected

You can use the small slider in the bottom right of the Project tab to change how your files are displayed.

So, you've just created a subfolder named Scripts, as shown in the preceding screenshot. Inside that parent folder, you 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 up automatically when you double-click any C# script from inside the editor.

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 Project tab.

Double-click on LearningCurve.cs, which will open up the C# file in Visual Studio:

Figure 1.19: LearningCurve C# script in Visual Studio

You can change the Visual Studio tabs at any time from Visual Studio | View | Layout. I'll be using the Design layout for the rest of the book so we can see our project files in the left-hand side of the editor.

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 started.

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 Figure 1.19 of the C# file in Visual Studio:

publicclassLearningCurve : 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.

If you were to rename the file at a later point, the filename would change, but line 5 would be as follows:

publicclassNewBehaviourScript : 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, as well as the name of the .meta file on your desktop. You can find the .meta file in the project folder under Assets | Scripts:

Figure 1.20: Finding the META file

Syncing C# files

As part of their symbiotic relationship, Unity and Visual Studio communicate 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, which states that "anything that can go wrong will go wrong," 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 in Unity, 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.

Every game object (an item in the Hierarchy window) in a scene has a Transform component that controls its Position, Rotation, and Scale. 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 game objectMove over to the Inspector tab and click on the information icon (question mark) at the top right of the Transform component:

Figure 1.21: Main Camera game object selected in the Inspector

You'll see a web browser open on the Transforms page of the Reference Manual:

Figure 1.22: Unity 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.

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 the SWITCH TO SCRIPTING link underneath the component or class name (Transform, in this case):

Figure 1.23: Unity Reference Manual with the SWITCH TO SCRIPTING button highlighted

By doing so, the Reference Manual automatically switches to the Scripting Reference:

Figure 1.24: Unity scripting documentation with SWITCH TO MANUAL highlighted

As you can see, as well as coding help, there is also an option to switch back to the Reference Manual if necessary.

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 Forum: https://forum.unity.com/Unity Answers: https://answers.unity.com/index.htmlUnity Discord: https://discord.com/invite/unity

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# resources. For starters, the Microsoft Learn documentation at https://docs.microsoft.com/en-us/dotnet/csharp has a ton of great tutorials, quickstart guides, and how-to articles. You can also find great overviews of individual C# topics at https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/index.

However, if you want detailed information on a specific C# language feature, the reference guides are the place to go. These reference guides are an important resource for any C# programmer, but since they aren't always the easiest to navigate, let's take a few minutes to learn how to find what we're looking for.

Let's load up the programming guide link and look up the C# String class. Do either of the following:

Enter Strings in the search bar in the top-left corner of the web pageScroll down to Language Sections and click on the Strings link directly:

Figure 1.25: Navigating Microsoft's C# reference guide

You should see something like the following for the class description page:

Figure 1.26: Microsoft's Strings (C# Programming Guide) page

Unlike Unity's documentation, the C# reference and scripting information is all bundled up into one, but its saving grace is the subtopic list on the right-hand side. Use it well! It's extremely important to know where to find help when you're stuck or have a question, so be sure to circle back to this section whenever you hit a roadblock.

Summary

We covered quite a bit of logistical information in this chapter, so I can understand if you're itching to write some code. Starting new projects, creating folders and scripts, and accessing documentation are topics that are easily forgotten in the excitement of a new adventure. Just remember that this chapter has a lot of resources you might need in the coming pages, so don't be afraid to come back and visit. Thinking like a programmer is a muscle: the more you work it, the stronger it gets.

In the next chapter, we'll start laying out the theory, vocabulary, and main concepts you'll need to prime your coding brain. Even though the material is conceptual, we'll still be writing our first lines of code in the LearningCurve script. Get ready!

Pop quiz – dealing with scripts

What type of relationship do Unity and Visual Studio share?The Scripting Reference supplies example code in regards to using a particular Unity component or feature. Where can you find more detailed (non-code-related) information about Unity components?The Scripting Reference is a large document. How much of it do you have to memorize before attempting to write a script?When is the best time to name a C# script?

JOIN us on Discord!

Read this book alongside other users, Unity/C# experts, and Harrison Ferrone. Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions and much more.

Join Now!

https://packt.link/csharpunity2021