Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning C# by Developing Games with Unity 2021
Learning C# by Developing Games with Unity 2021

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

eBook
$9.99 $49.99
Paperback
$62.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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 feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning C# by Developing Games with Unity 2021

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!

Understanding methods

On their own, variables can't do much more than keep track of their assigned values. While this is vital, they are not very useful on their own in terms of creating meaningful applications. So, how do we go about creating actions and driving behavior in our code? The short answer is by using methods.

Before we get to what methods are and how to use them, we should clarify a small point of terminology. In the world of programming, you'll commonly see the terms method and function used interchangeably, especially in regards to Unity.

Since C# is an object-oriented language (this is something that we'll cover in Chapter 5, Working with Classes, Structs, and OOP), we'll be using the term method for the rest of the book to conform to standard C# guidelines.

When you come across the word function in the Scripting Reference or any other documentation, think method.

Methods drive actions

Similarly to variables, defining programming methods can be tediously long-winded or dangerously brief; here's another three-pronged approach to consider:

  • Conceptually, methods are how work gets done in an application.
  • Technically, a method is a block of code containing executable statements that run when the method is called by name. Methods can take in arguments (also called parameters), which can be used inside the method's scope.
  • Practically, a method is a container for a set of instructions that run every time it's executed. These containers can also take in variables as inputs, which can only be referenced inside the method itself.

Taken all together, methods are the bones of any program—they connect everything and almost everything is built off of their structure.

You can find an in-depth guide to methods in the Microsoft C# documentation at https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods.

Methods are placeholders too

Let's take an oversimplified example of adding two numbers together to drive the concept home. When writing a script, you're essentially laying down lines of code for the computer to execute in sequential order. The first time you need to add two numbers together, you could just add them like in the following code block:

SomeNumber + AnotherNumber

But then you conclude that these numbers need to be added together somewhere else.

Instead of copying and pasting the same line of code, which results in sloppy or "spaghetti" code and should be avoided at all costs, you can create a named method that will take care of this action:

AddNumbers() 
{
    SomeNumber + AnotherNumber
}

Now AddNumbers is holding a place in memory, just like a variable; however, instead of a value, it holds a block of instructions. Using the name of the method (or calling it) anywhere in a script puts the stored instructions at your fingertips without having to repeat any code.

If you find yourself writing the same lines of code over and over, you're likely missing a chance to simplify or condense repeated actions into common methods.

This produces what programmers jokingly call spaghetti code because it can get messy. You'll also hear programmers refer to a solution called the Don't Repeat Yourself (DRY) principle, which is a mantra you should keep in mind.

As before, once we've seen a new concept in pseudocode, it's best if we implement it ourselves, which is what we'll do in the next section to drive it home.

Let's open up LearningCurve again and see how a method works in C#. Just like with the variables example, you'll want to copy the code into your script exactly as it appears in the following screenshot. I've deleted the previous example code to make things neater, but you can, of course, keep it in your script for reference:

  1. Open up LearningCurve in Visual Studio.
  2. Add a new variable to line 8:
    public int AddedAge = 1;
    
  3. Add a new method to line 16 that adds CurrentAge and AddedAge together and prints out the result:
    void ComputeAge() 
    {
        Debug.Log(CurrentAge + AddedAge);
    }
    
  4. Call the new method inside Start with the following line:
        ComputeAge();
    

    Double-check that your code looks like the following screenshot before you run the script in Unity:

    Figure 2.6: LearningCurve with new ComputeAge method

  5. Save the file, and then go back and hit play in Unity to see the new Console output.

You defined your first method on lines 16 to 19 and called it on line 13. Now, wherever ComputeAge() is called, the two variables will be added together and printed to the console, even if their values change. Remember, you set CurrentAge to 18 in the Unity Inspector, and the Inspector value will always override the value in a C# script:

Figure 2.7: Console output from changing the variable value in the Inspector

Go ahead and try out different variable values in the Inspector panel to see this in action! More details on the actual code syntax of what you just wrote are coming up in the next chapter.

With a bird's-eye view of methods under our belts, we're ready to tackle the biggest topic in the programming landscape—classes!

Introducing classes

We've seen how variables store information and how methods perform actions, but our programming toolkit is still somewhat limited. We need a way of creating a sort of super container, containing variables and methods that can be referenced from within the container itself. Enter classes:

  • Conceptually, a class holds related information, actions, and behaviors inside a single container. They can even communicate with each other.
  • Technically, classes are data structures. They can contain variables, methods, and other programmatic information, all of which can be referenced when an object of the class is created.
  • Practically, a class is a blueprint. It sets out the rules and regulations for any object (called an instance) created using the class blueprint.

You've probably realized that classes surround us not only in Unity but in the real world as well. Next, we'll take a look at the most common Unity class and how classes function in the wild.

You can find an in-depth guide to classes in the Microsoft C# documentation at https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/classes.

A common Unity class

Before you wonder what a class looks like in C#, you should know that you've been working with a class this whole chapter. By default, every script created in Unity is a class, which you can see from the class keyword on line 5:

public class LearningCurve: MonoBehaviour

MonoBehaviour just means that this class can be attached to a GameObject in the Unity scene.

Classes can exist on their own, which we'll see when we create standalone classes in Chapter 5, Working with Classes, Structs, and OOP.

The terms script and class are sometimes used interchangeably in Unity resources. For consistency, I'll be referring to C# files as scripts if they're attached to GameObjects and as classes if they are standalone.

Classes are blueprints

For our last example, let's think about a local post office. It's a separate, self-contained environment that has properties, such as a physical address (a variable), and the ability to execute actions, such as sending out your mail (methods).

This makes a post office a great example of a potential class that we can outline in the following block of pseudocode:

public class PostOffice
{
    // Variables
    public string address = "1234 Letter Opener Dr."
    // Methods
    DeliverMail() {}
    SendMail() {}
}

The main takeaway here is that when information and behaviors follow a predefined blueprint, complex actions and inter-class communication become possible. For instance, if we had another class that wanted to send a letter through our PostOffice class, it wouldn't have to wonder where to go to fire this action. It could simply call the SendMail function from the PostOffice class, as follows:

PostOffice().SendMail()

Alternatively, you could use it to look up the address of the post office so you know where to post your letters:

PostOffice().address

If you're wondering about the use of periods (called dot notation) between words, we'll be diving into that in the next section—hold tight.

Communication among classes

Up until now, we've described classes and, by extension, Unity components as separate standalone entities; in reality, they are deeply intertwined. You'd be hard-pressed to create any kind of meaningful software application without invoking some kind of interaction or communication between classes.

If you remember the post office example from earlier, the example code made use of periods (or dots) to reference classes, variables, and methods. If you think of classes as directories of information, then dot notation is the indexing tool:

PostOffice().Address

Any variables, methods, or other data types within a class can be accessed with dot notation. This applies to nested, or subclass, information as well, but we'll tackle all those subjects when we get to Chapter 5, Working with Classes, Structs, and OOP.

Dot notation is also what drives communication between classes. Whenever a class needs information about another class or wants to execute one of its methods, dot notation is used:

PostOffice().DeliverMail()

Dot notation is sometimes referred to as the . operator, so don't be thrown off if you see it mentioned this way in documentation.

If dot notation doesn't quite click with you yet, don't worry, it will. It's the bloodstream of the entire programming body, carrying information and context wherever it's needed.

Now that you know a little more about classes, let's talk about the tool you'll use the most in your programming career—comments!

Working with comments

You might have noticed that LearningCurve has an odd line of text (10 in Figure 2.6) starting with two forward slashes, which were created by default with the script.

These are code comments! In C#, there are a few ways that you can use to create comments, and Visual Studio (and other code editing applications) will often make it even easier with built-in shortcuts.

Some professionals wouldn't call commenting an essential building block of programming, but I'll have to respectfully disagree. Correctly commenting out your code with meaningful information is one of the most fundamental habits a new programmer can develop.

Single-line comments

The following single-line comment is like the one we've included in LearningCurve:

// This is a single-line comment

Visual Studio doesn't compile lines starting with two forward slashes (without empty space) as code, so you can use them as much as needed to explain your code to others or your future self.

Multi-line comments

Since it's in the name, you'd be right to assume that single-line comments only apply to one line of code. If you want multi-line comments, you'll need to use a forward slash and an asterisk, (/* and */ as opening and closing characters respectively) around the comment text:

/* this is a 
      multi-line comment */ 

You can also comment and uncomment blocks of code by highlighting them and using the Cmd + / shortcut on macOS and Ctrl + K + C on Windows.

Visual Studio also provides a handy auto-generated commenting feature; type in three forward slashes on the line preceding any line of code (variables, methods, classes, and more) and a summary comment block will appear.

Seeing example comments is good, but putting them in your code is always better. It's never too early to start commenting!

Adding comments

Open up LearningCurve and add in three backslashes above the ComputeAge() method:

Figure 2.8: Triple-line comment automatically generated for a method

You should see a three-line comment with a description of the method generated by Visual Studio from the method's name, sandwiched between two <summary> tags. You can, of course, change the text, or add new lines by hitting Enter just as you would in a text document; just make sure not to touch the <summary> tags or Visual Studio won't recognize the comments correctly.

The useful part about these detailed comments is clear when you want to know something about a method you've written. If you've used a triple forward slash comment, all you need to do is hover over the method name anywhere it's called within a class or script, and Visual Studio will pop your summary:

Figure 2.9: Visual Studio pop-up info box with the comment summary

Your basic programming toolkit is now complete (well, the theory drawer, at least). However, we still need to understand how everything we've learned in this chapter applies in the Unity game engine, which is what we'll be focusing on in the next section!

Putting the building blocks together

With the building blocks squared away, it's time to do a little Unity-specific housekeeping before wrapping up this chapter. Specifically, we need to know more about how Unity handles C# scripts attached to game objects.

For this example, we'll keep using our LearningCurve script and Main Camera GameObject.

Scripts become components

All GameObject components are scripts, whether they're written by you or the good people at Unity. The only difference is that Unity-specific components such as Transform, and their respective scripts just aren't supposed to be edited by users.

The moment a script that you have created is dropped onto a GameObject, it becomes another component of that object, which is why it appears in the Inspector panel. To Unity, it walks, talks, and acts like any other component, complete with public variables underneath the component that can be changed at any time. Even though we aren't supposed to edit the components provided by Unity, we can still access their properties and methods, making them powerful development tools.

Unity also makes some automatic readability adjustments when a script becomes a component. You might have noticed in Figures 2.3 and 2.5 that when we added LearningCurve to Main Camera, Unity displayed it as Learning Curve, with CurrentAge changing to Current Age.

We looked at how to update a variable in the Inspector panel in the Variables act as placeholders section, but it's important to touch on how this works in more detail. There are three situations in which you can modify a property value:

  • In Play Mode in the Unity Editor window
  • In Development Mode in the Unity Editor window
  • In the Visual Studio code editor

Changes made in Play Mode take effect in real time, which is great for testing and fine-tuning gameplay. However, it's important to note that any changes made while in Play Mode will be lost when you stop the game and return to Development Mode.

When you're in Development Mode, any changes that you make to the variables will be saved by Unity. This means that if you were to quit Unity and then restart it, the changes would be retained.

The changes that you make to values in the Inspector panel while in Play Mode do not modify your script, but they will override any values you had assigned in your script when in Development Mode.

Any changes made in Play Mode will always reset automatically when you stop Play Mode. If you need to undo any changes made in the Inspector panel, you can reset the script to its default (sometimes called initial) values. Click on the three vertical dots icon to the right of any component, and then select Reset, as shown in the following screenshot:

Figure 2.10: Script reset option in the Inspector

This should give you some peace of mind—if your variables get out of hand, there's always the hard reset.

A helping hand from MonoBehaviour

Since C# scripts are classes, how does Unity know to make some scripts components and not others? The short answer is that LearningCurve (and any script created in Unity) inherits from MonoBehaviour (a default class provided by Unity). This tells Unity that the C# class can be transformed into a component.

The topic of class inheritance is a bit advanced for this point of your programming journey; think of it as the MonoBehaviour class lending a few of its variables and methods to LearningCurve. Chapter 5, Working with Classes, Struct, and OOP, will cover class inheritance in practical detail.

The Start() and Update() methods that we've used belong to MonoBehaviour, which Unity runs automatically on any script attached to a GameObject. The Start() method runs once when the scene starts playing, while the Update() method runs once per frame (depending on the frame rate of your machine).

Now that your familiarity with Unity's documentation has gotten a nice bump, I've put together a short optional challenge for you to tackle!

Hero's trial – MonoBehaviour in the Scripting API

Now it's time for you to get comfortable using the Unity documentation on your own, and what better way than to look up some of the common MonoBehaviour methods:

  • Try searching for the Start() and Update() methods in the Scripting API to gain a better understanding of what they do in Unity, and when
  • If you're feeling brave, go the extra step and have a look at the MonoBehaviour class in the manual for a more detailed explanation

Summary

We've come a long way in a few short pages, but understanding the overarching theory of fundamental concepts such as variables, methods, and classes will give you a strong foundation to build on. Bear in mind that these building blocks have very real counterparts in the real world. Variables hold values like mailboxes hold letters; methods store instructions like recipes, to be followed for a predefined result; and classes are blueprints just like real blueprints. You can't build a house without a well-thought-out design to follow if you expect it to stay standing.

The rest of this book will take you on a deep dive into C# syntax from scratch, starting with more detail in the next chapter on how to create variables, manage value types, and work with simple and complex methods.

Pop quiz – C# building blocks

  1. What is the main purpose of a variable?
  2. What role do methods play in scripts?
  3. How does a script become a component?
  4. What is the purpose of dot notation?

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

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.

Who is this book for?

If you're a developer, programmer, hobbyist, or anyone who wants to get started with Unity and C# programming in a fun and engaging manner, this book is for you. You’ll still be able to follow along if you don’t have programming experience, but knowing the basics will help you get the most out of this book.

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
Estimated delivery fee Deliver to Malaysia

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

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

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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 feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Malaysia

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

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

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 $ 161.97
Learning C# by Developing Games with Unity 2021
$62.99
Hands-On Unity 2021 Game Development
$43.99
Unity 2021 Cookbook
$54.99
Total $ 161.97 Stars icon
Banner background image

Table of Contents

17 Chapters
Getting to Know Your Environment Chevron down icon Chevron up icon
The Building Blocks of Programming Chevron down icon Chevron up icon
Diving into Variables, Types, and Methods Chevron down icon Chevron up icon
Control Flow and Collection Types Chevron down icon Chevron up icon
Working with Classes, Structs, and OOP Chevron down icon Chevron up icon
Getting Your Hands Dirty with Unity Chevron down icon Chevron up icon
Movement, Camera Controls, and Collisions Chevron down icon Chevron up icon
Scripting Game Mechanics Chevron down icon Chevron up icon
Basic AI and Enemy Behavior Chevron down icon Chevron up icon
Revisiting Types, Methods, and Classes Chevron down icon Chevron up icon
Introducing Stacks, Queues, and HashSets Chevron down icon Chevron up icon
Saving, Loading, and Serializing Data Chevron down icon Chevron up icon
Exploring Generics, Delegates, and Beyond Chevron down icon Chevron up icon
The Journey Continues Chevron down icon Chevron up icon
Pop Quiz Answers Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(36 Ratings)
5 star 83.3%
4 star 11.1%
3 star 0%
2 star 2.8%
1 star 2.8%
Filter icon Filter
Top Reviews

Filter reviews by




Thomas Lane Feb 11, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I can't speak more highly about this book and the author. I've searched far for a book that teaches Unity in the way this does.Unity's own tutorials while I believe are useful, tend to not show you the absolute base stuff which I feel like this book does perfectly, especially with dealing with primitives. Also the thing I really like about this book is that it starts you out with the coding and not making you navigate Unitys UI right off the bat. I feel like that is a vastly important decision that really makes this book perfect if you're the type of learning I am. To me, I learn more by making stuff work in code then with a GUI, and this book perfectly mixes the two with more of a reliance on the former.
Amazon Verified review Amazon
Forrest Severson May 23, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is wonderful and helped me relearn Unity after getting out of the Army.
Amazon Verified review Amazon
Jarvis Hill Jan 24, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Learning C# by Developing Games is a really great book to pick up if you're trying to get into unity development. The book initially walks you through everything you need to know to get started. The early chapters familiarized you with C# and Visual Studio editor. Then you’ll go over everything you need to know about the fundamentals of programming. You’ll review the basics like variables and methods. As you get deeper into the book you gain more in-depth knowledge. The book does a great job of teaching you how to control the flow of the code through the use of If and Switch conditional Statements which makes it easier to work with collections like Arrays, List, and Dictionaries. You’ll end up gaining a better understanding of Object Oriented Programing. Later chapters will explain the differences between Classes and Struct and went to use them. As you make your way towards the end of the book you will start to learn more complex things like How to code the Gameplay Mechanics, control and move your player, and how to code the Enemy AI’s movement and Behaviors. You even learn how to save and load the game's data using JSON and XML. This book is a great read and I highly recommend it.
Amazon Verified review Amazon
Rich Tanner Nov 12, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This text is a great introduction to both Unity and to C#, and serves as a wonderful refresher if you’ve experience in either topic.I’ve been playing in both C# and Unity for years now, and I even found a few brand new tidbits among the fun projects within.I plan to assign this resource for future college courses, and, quite frankly, this is the textbook I wish I had written myself!Great work Harrison Ferrone and Packt!
Amazon Verified review Amazon
Jonathan Ball Jun 08, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a very inspirational and informative book. I already have some C# experience but had 0 experience with Unity and found it to be a fantastic intro. The simple game that you will build from this book is very exciting for a newcomer and I highly recommend it to anyone that loves video games and wants to become a .net / C# developer.This book is however not the be all and end all to C# programming as the author will even tell you so you will still need to keep learning C# after the book is done to become anything of a decent C# programmer.I did not buy this book from Amazon but from Packt publishing so that is why I am not a verified purchaser although Kindle is an amazing book reading app so perhaps have a look at the Kindle edition on Amazon.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela