Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning C# by Developing Games with Unity 2021 - Sixth Edition
Learning C# by Developing Games with Unity 2021 - Sixth Edition

Learning C# by Developing Games with Unity 2021: Kickstart your C# programming and Unity journey by building 3D games from scratch, Sixth Edition

Profile Icon Harrison Ferrone
By Harrison Ferrone
$34.98 $49.99
Book Oct 2021 428 pages 6th Edition
eBook
$34.98 $49.99
Print
$62.99
Subscription
Free Trial
Renews at $19.99p/m
Profile Icon Harrison Ferrone
By Harrison Ferrone
$34.98 $49.99
Book Oct 2021 428 pages 6th Edition
eBook
$34.98 $49.99
Print
$62.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$34.98 $49.99
Print
$62.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Learning C# by Developing Games with Unity 2021 - Sixth Edition

The Building Blocks of Programming

Any programming language starts off looking like ancient Greek to the unaccustomed eye, and C# is no exception. The good news is beneath the initial mystery, all programming languages are made up of the same essential building blocks. Variables, methods, and classes (or objects) make up the DNA of conventional programming; understanding these simple concepts opens up an entire world of diverse and complex applications. After all, there are only four different DNA nucleobases in every person on earth; yet, here we are, every one of us a unique organism.

If you are new to programming, there's going to be a lot of information coming at you in this chapter, and this could mark the first lines of code that you've ever written. The point is not to overload your brain with facts and figures; it's to give you a holistic look at the building blocks of programming using examples from everyday life.

This chapter is all about the high-level view of the bits and pieces that make up a program. Getting the hang of how things work before getting into the code directly will not only help you new coders find your feet, but it will also solidify the topics with easy-to-remember references. Ramblings aside, we'll focus on the following topics throughout this chapter:

  • Defining variables
  • Understanding methods
  • Introducing classes
  • Working with comments
  • Putting the building blocks together

Defining variables

Let's start with a simple question: what is a variable? Depending on your point of view, there are a few different ways of answering that question:

  • Conceptually, a variable is the most basic unit of programming, as an atom is to the physical world (excepting string theory). Everything starts with variables, and programs can't exist without them.
  • Technically, a variable is a tiny section of your computer's memory that holds an assigned value. Every variable keeps track of where its information is stored (this is called a memory address), its value, and its type (for instance, numbers, words, or lists).
  • Practically, a variable is a container. You can create new ones at will, fill them with stuff, move them around, change what they're holding, and reference them as needed. They can even be empty and still be useful.

You can find an in-depth explanation of variables in the Microsoft C# documentation at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables.

A practical real-life example of a variable is a mailbox—remember those?

Figure 2.1: Snapshot of a row of colorful mailboxes

They can hold letters, bills, a picture from your aunt Mabel—anything. The point is that what's in a mailbox can vary: they can have names, hold information (physical mail), and their contents can even be changed if you have the right security clearance. Similarly, variables can hold different kinds of information. Variables in C# can hold strings (text), integers (numbers), and even Booleans (binary values that represent either true or false).

Names are important

Referring to Figure 2.1, if I asked you to go over and open the mailbox, the first thing you'd probably ask is: which one? If I said the Smith family mailbox, or the sunflower mailbox, or even the droopy mailbox on the far right, then you'd have the necessary context to open the mailbox I was referencing. Similarly, when you are creating variables, you have to give them unique names that you can reference later. We'll get into the specifics of proper formatting and descriptive naming in Chapter 3, Diving into Variables, Types, and Methods.

Variables act as placeholders

When you create and name a variable, you are creating a placeholder for the value that you want to store. Let's take the following simple math equation as an example:

2 + 9 = 11

Okay, no mystery here, but what if we wanted the number 9 to be its variable? Consider the following code block:

MyVariable = 9

Now we can use the variable name, MyVariable, as a substitute for 9 anywhere we need it:

2 + MyVariable = 11

If you're wondering whether variables have other rules or regulations, they do. We'll get to those in the next chapter, so sit tight.

Even though this example isn't real C# code, it illustrates the power of variables and their use as placeholder references. In the next section you'll start creating variables of your own, so keep going!

Alright, enough theory—let's create a real variable in the LearningCurve script we created in Chapter 1, Getting to Know Your Environment:

  1. Double-click on LearningCurve.cs from the Unity project window to open it in Visual Studio.
  2. Add a space between lines 6 and 7 and add the following line of code to declare a new variable:
    public int CurrentAge = 30;
    
  3. Inside the Start method, add two debug logs to print out the following calculations:
        Debug.Log(30 + 1);
        Debug.Log(CurrentAge + 1);
    

Let's break down the code we just added. First, we created a new variable called CurrentAge and assigned it a value of 30. Then, we added two debug logs to print out the result of 30 + 1 and CurrentAge + 1 to show how variables are storage for values. They can be used the exact same way as the values themselves.

It's also important to note that public variables appear in the Unity Inspector, while private ones don't. Don't worry about the syntax right now—just make sure your script is the same as the script that is shown in the following screenshot:

Figure 2.2: LearningCurve script open in Visual Studio

To finish, save the file using Editor | File | Save.

For scripts to run in Unity, they have to be attached to GameObjects in the scene. The sample scene in Hero Born has a camera and directional light by default, which provides the lighting for the scene, so let's attach LearningCurve to the camera to keep things simple:

  1. Drag and drop LearningCurve.cs onto the Main Camera.
  2. Select the Main Camera so that it appears in the Inspector panel, and verify that the LearningCurve.cs (Script) component is attached properly.
  3. Click play and watch for the output in the Console panel:

    Figure 2.3: Unity Editor window with callouts for dragging and dropping scripts

The Debug.Log() statements printed out the result of the simple math equations we put in between the parentheses. As you can see in the following Console screenshot, the equation that used our variable, CurrentAge, worked the same as if it were a real number:

Figure 2.4: Unity console with debug output from the attached script

We'll get into how Unity converts C# scripts into components at the end of this chapter, but first, let's work on changing the value of one of our variables.

Since CurrentAge was declared as a variable on line 7 as shown in Figure 2.2, the value it stores can be changed. The updated value will then trickle down to wherever the variable is used in code; let's see this in action:

  1. Stop the game by clicking the Pause button if the scene is still running
  2. Change Current Age to 18 in the Inspector panel and play the scene again, looking at the new output in the Console panel:

    Figure 2.5: Unity console with debug logs and the LearningCurve script attached to Main Camera

The first output will still be 31 because we didn't change anything in the script, but the second output is now 19 because we changed the value of CurrentAge in the Inspector.

The goal here wasn't to go over variable syntax but to show how variables act as containers that can be created once and referenced elsewhere. We'll go into more detail in Chapter 3, Diving into Variables, Types, and Methods.

Now that we know how to create variables in C# and assign them values, we're ready to dive into the next important programming building block: methods!

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn C# programming basics, terminology, and coding best practices
  • Become confident with Unity fundamentals and features in line with Unity 2021
  • Apply your C# knowledge in practice and build a working first-person shooter game prototype in Unity

Description

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.

What you will learn

  • Follow simple steps and examples to create and implement C# scripts in Unity
  • Develop a 3D mindset to build games that come to life
  • Create basic game mechanics such as player controllers and shooting projectiles using C#
  • Divide your code into pluggable building blocks using interfaces, abstract classes, and class extensions
  • Become familiar with stacks, queues, exceptions, error handling, and other core C# concepts
  • Learn how to handle text, XML, and JSON data to save and load your game data
  • Explore the basics of AI for games and implement them to control enemy behavior

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 29, 2021
Length 428 pages
Edition : 6th Edition
Language : English
ISBN-13 : 9781801813945
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Oct 29, 2021
Length 428 pages
Edition : 6th Edition
Language : English
ISBN-13 : 9781801813945
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together

Stars icon
Total $ 89.96 129.97 40.01 saved
Learning C# by Developing Games with Unity 2021
$34.98 $49.99
Hands-On Unity 2021 Game Development
$24.99 $35.99
Unity 2021 Cookbook
$29.99 $43.99
=
Book stack Total $ 89.96 129.97 40.01 saved Stars icon

Table of Contents

18 Chapters
Preface Chevron down icon Chevron up icon
1. Getting to Know Your Environment Chevron down icon Chevron up icon
2. The Building Blocks of Programming Chevron down icon Chevron up icon
3. Diving into Variables, Types, and Methods Chevron down icon Chevron up icon
4. Control Flow and Collection Types Chevron down icon Chevron up icon
5. Working with Classes, Structs, and OOP Chevron down icon Chevron up icon
6. Getting Your Hands Dirty with Unity Chevron down icon Chevron up icon
7. Movement, Camera Controls, and Collisions Chevron down icon Chevron up icon
8. Scripting Game Mechanics Chevron down icon Chevron up icon
9. Basic AI and Enemy Behavior Chevron down icon Chevron up icon
10. Revisiting Types, Methods, and Classes Chevron down icon Chevron up icon
11. Introducing Stacks, Queues, and HashSets Chevron down icon Chevron up icon
12. Saving, Loading, and Serializing Data Chevron down icon Chevron up icon
13. Exploring Generics, Delegates, and Beyond Chevron down icon Chevron up icon
14. The Journey Continues Chevron down icon Chevron up icon
15. Pop Quiz Answers Chevron down icon Chevron up icon
16. Other Books You May Enjoy Chevron down icon Chevron up icon
17. Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.