
Learning C# by Developing Games with Unity 6
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
It's the ability to write custom C# scripts for behaviors and game mechanics that really takes Unity the extra mile. That's where this book will help you as a new programmer! Harrison Ferrone, in this eighth edition of the bestselling series, will take you through the core concepts of programming and the C# language from scratch, while building an engaging and playable game prototype in Unity 6. You'll get to grips with the fundamentals of object-oriented programming (OOP) and the Unity engine with lots of code samples, exercises, and tips to go beyond the book with your work. You'll write C# scripts for simple game mechanics, perform procedural programming, request live data from the web, and add complexity to your games by introducing intelligent enemies and damage-dealing projectiles. You'll also explore the underlying mechanics of Unity game development, including game design, lighting basics, player movement, camera controls, collisions, and more, with every passing chapter. Note: The screenshots in the book display the Unity Editor in full-screen mode for a comprehensive view. You can easily reference color versions of images by downloading them from the GitHub repository or the graphics bundle linked in the book.
All prices
More details
Content
- Cover
- Copyright
- Foreword
- Contributors
- Table of Contents
- Preface
- Chapter 1: Getting to Know Your Environment
- Getting the most out of this book - get to know your free benefits
- Next-gen reader
- Interactive AI assistant (beta)
- DRM-free PDF or ePub version
- Technical requirements
- Getting started with Unity 6
- Using macOS
- Creating a new project
- Navigating the editor
- Using C# with Unity
- Setting up Visual Studio Code in Unity 6
- Working with C# scripts
- Introducing the Visual Studio Code 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
- Chapter 2: 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
- Unity application lifecycle
- Summary
- Pop quiz: C# building blocks
- Chapter 3: 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 variable types
- Common built-in types
- Type conversions
- Inferred declarations
- Custom types
- Naming variables
- Understanding variable scope
- Introducing operators
- Understanding methods
- Declaring methods
- Naming methods
- 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
- Chapter 4: Control Flow and Collection Types
- Selection statements
- The if-else statement
- Using the NOT operator
- Nesting statements
- Evaluating multiple conditions
- Putting it all together
- The switch statement
- Pattern matching
- Fall-through cases
- Pop quiz 1: if, and, or but
- Collections at a glance
- Arrays
- Indexing and subscripts
- Multidimensional arrays
- Range exceptions
- Lists
- Setting up a list
- Accessing and modifying lists
- Dictionaries
- Creating a dictionary
- Working with dictionary pairs
- Pop quiz 2: all about collections
- Iteration statements
- for loops
- foreach loops
- Looping through key-value pairs
- Hero's trial: finding affordable items
- while loops
- To infinity and beyond
- Summary
- Chapter 5: Working with Classes, Structs, and OOP
- Introducing OOP
- Defining classes
- Creating a class
- 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
- Chapter 6: Getting Your Hands Dirty with Unity
- A game design primer
- Game design documents
- The Hero Born one-pager
- Building a level
- Creating primitives
- Thinking in 3D
- Applying materials
- White-boxing
- Editor tools
- Hero's trial: putting up drywall
- Keeping the hierarchy clean
- Working with Prefabs
- Hero's trial: creating a health pickup
- 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
- Chapter 7: 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
- Chapter 8: Scripting Game Mechanics
- Making the player jump
- 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
- Chapter 9: Basic AI and Enemy Behavior
- Navigating 3D space in Unity
- Unity's navigation components
- Adding a NavMeshSurface
- 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
- Chapter 10: Revisiting Types, Methods, and Classes
- Access modifiers
- Constant and read-only properties
- Using static classes
- 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
- Chapter 11: Specialized Collection Types and LINQ
- Introducing stacks
- Popping and peeking
- Common methods in a stack class
- Working with queues
- Adding, removing, and peeking
- Using HashSets
- Performing set operations
- Querying data with LINQ
- LINQ basics
- Lambda expressions
- Chaining queries
- Transforming data into new types
- Simplifying with optional syntax
- Summary
- Pop quiz: Intermediate collections
- Chapter 12: 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 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
- Chapter 13: Connecting to the World Wide Web
- The web request blueprint
- Creating the request manager
- Formatting a URL
- Configuring the web request
- Synchronous versus asynchronous code
- Using Unity coroutines
- Managing request responses
- Deserializing request data
- Adjusting the game lighting
- Additional web request formats
- Summary
- Pop quiz: Requesting data
- Chapter 14: Exploring Generics, Delegates, and Beyond
- Introducing generics
- Generic classes
- 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#
- Chapter 15: 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
- Chapter 16: Unlock Your Book'sExclusive Benefits
- How to unlock these benefits in three easy steps
- Pop Quiz Answers
- Other Books You May Enjoy
- Index
Preface
Unity is one of the most popular game engines in the world, catering to hobbyists, professional AAA studios, and cinematic production companies. While known for its use as a 3D tool, Unity has a host of dedicated features supporting everything from 2D games and virtual reality to post-production and cross-platform publishing.
Developers love its drag-and-drop interface and built-in features, but it's the ability to write custom C# scripts for behaviors and game mechanics that really takes Unity the extra mile. Learning how to write C# code might not be a huge obstacle to a seasoned programmer with other languages under their belt, but it can be daunting for those of you who have no programming experience. That's where this book comes in, as I'll be taking you through the building blocks of programming and the C# language from scratch while building a fun and playable game prototype in Unity.
Who this book is for
This book is written for those of you who don't have any experience with the basic tenets of programming or C#. However, if you're a competent novice or seasoned professional coming from another language, or even C#, but need to get hands-on with game development in Unity, this is still where you want to be.
What this book covers
Chapter 1, Getting to Know Your Environment, starts off with the Unity installation process, the main features of the editor, and finding documentation for C# and Unity-specific topics. We'll also go through creating C# scripts from inside Unity and look at Visual Studio, the application where all our code editing takes place.
Chapter 2, The Building Blocks of Programming, begins by laying out the atomic-level concepts of programming, giving you the chance to relate variables, methods, and classes to situations in everyday life. From there, we'll move on to simple debugging techniques, proper formatting and commenting, and how Unity turns C# scripts into components.
Chapter 3, Diving into Variables, Types, and Methods, takes a deeper look at the building blocks from Chapter 2. This includes C# data types, naming conventions, access modifiers, and everything else you'll need for the foundation of a program. We'll also go over how to write methods, add parameters, and use return types, ending with an overview of standard Unity methods belonging to the MonoBehaviour class.
Chapter 4, Control Flow and Collection Types, introduces the common approaches to making decisions in code, consisting of the if...else and switch statements. From there, we'll move on to working with arrays, lists, and dictionaries, and incorporating iteration statements for looping through collection types. We'll end the chapter with a look at conditional looping statements and a special C# data type called enumerations.
Chapter 5, Working with Classes, Structs, and OOP, details our first contact with constructing and instantiating classes and structs. We'll go through the basic steps of creating constructors, adding variables and methods, and the fundamentals of subclassing and inheritance. The chapter will end with a comprehensive explanation of object-oriented programming (OOP) and how it applies to C#.
Chapter 6, Getting Your Hands Dirty with Unity, marks our departure from C# syntax into the world of game design, level building, and Unity's featured tools. We'll start by going over the basics of a game design document and then move on to blocking out our level geometry and adding lighting and a simple particle system.
Chapter 7, Movement, Camera Controls, and Collisions, explains different approaches to moving a player object and setting up a third-person camera. We'll discuss incorporating Unity physics for more realistic locomotion effects, as well as how to work with collider components and capture interactions within a scene.
Chapter 8, Scripting Game Mechanics, introduces the concept of game mechanics and how to effectively implement them. We'll start by adding a simple jump action, creating a shooting mechanic, and building on the previous chapters' code by adding logic to handle item collection.
Chapter 9, Basic AI and Enemy Behavior, starts with a brief overview of artificial intelligence (AI) in games and the concepts we will be applying to Hero Born. Topics covered in this chapter will include navigation in Unity, using the level geometry and a navigation mesh, smart agents, and automated enemy movement.
Chapter 10, Revisiting Types, Methods, and Classes, takes a more in-depth look at data types, intermediate method features, and additional behaviors that can be used for more complex classes. This chapter will give you a deeper understanding of the versatility and breadth of the C# language.
Chapter 11, Specialized Collection Types and LINQ, dives into stacks, queues, hash sets, and the different development scenarios that each is uniquely suited for. This chapter also explores filtering, ordering, and transforming data collections using LINQ.
Chapter 12, Saving, Loading, and Serializing Data, gets you ready to handle your game's information. Topics covered in this chapter include working with the filesystem and creating, deleting, and updating files. We'll also cover different data types, including XML, JSON, and binary data, and end with a practical discussion on serializing C# objects directly into data formats.
Chapter 13, Connecting to the World Wide Web, introduces the basics of web requests, downloading data from web servers, and turning that information into actionable game mechanics. We'll also cover the differences between synchronous and asynchronous code and how Unity handles both.
Chapter 14, Exploring Generics, Delegates, and Beyond, details intermediate features of the C# language and how to apply them in practical, real-world scenarios. We'll start with an overview of generic programming and progress to concepts such as delegation, events, and exception handling.
Chapter 15, The Journey Continues, reviews the main topics you've learned throughout the book and leaves you with resources for further study in both C# and Unity. Included in these resources will be online reading material, certifications, and a host of my favorite video tutorial channels.
To get the most out of this book
The only thing you need to get the most from your upcoming C# and Unity adventure is a curious mind and a willingness to learn. Having said that, doing all the code exercises, Hero's trials, and Quiz sections is a must if you hope to cement the knowledge you're learning. Lastly, revisiting topics and entire chapters to refresh or solidify your understanding before moving on is always a good idea. There is no sense in building a house on an unstable foundation.
You'll also need a current version of Unity installed on your computer-version 6.0 or later is recommended. All code examples have been tested with Unity 6000.0.50f1 and should work with future versions without issues.
This is the software/hardware covered in the book:
- Unity 6.0 or later
- Visual Studio 2019 or later
- C# 9.0 or later
Before starting, check that your computer setup meets the Unity system requirements at https://docs.unity3d.com/6000.0/Documentation/Manual/system-requirements.html.
Download the example code files
The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Learning-C-by-Developing-Games-with-Unity-6_8th-Edn.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing. Check them out!
Download the color images
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781805808718.
This book contains long screenshots captured to provide you with an overview of the entire Unity window. As a result, the text on these images may appear small at 100% zoom. We recommend referring to the graphics bundle for ease of understanding.
Conventions used
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and X/Twitter handles. For example: "For simple text or individual variables, use the standard Debug.Log() method."
A block of code is set as follows:
public int CurrentAge = 30; Any command-line input or output is written as follows:
[12:58:12] Player detected - attack! UnityEngine.Debug:Log (object) [12:58:15] Player deaths: 0 UnityEngine.Debug:Log (object) [12:58:18] Player deaths: 1 UnityEngine.Debug:Log (object) [12:58:18] Next time you'll be at number 2 UnityEngine.Debug:Log (object) Bold: Indicates a new term, an important word,...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: ePUB
Copy protection: without DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Use a reader that can handle the file format ePUB, such as Adobe Digital Editions or FBReader – both free (see eBook Help).
- Tablet/Smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePUB works well for novels and non-fiction books – i.e., 'flowing' text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook does not use copy protection or Digital Rights Management
For more information, see our eBook Help page.