Learning C# by Developing Games with Unity 5.x - Second Edition
By Lukosek Greg
5/5
()
About this ebook
About This Book
- Get to grips with the fundamentals of scripting in C# with Unity
- Create an awesome, 2D platformer game from scratch using the principles of object-oriented programming and coding in C#
- This is a step-by-step guide to learn the fundamentals of C# scripting to develop GameObjects and master the basics of the new UI system in Unity
Who This Book Is For
The book is targeted at beginner level Unity developers with no programming experience. If you are a Unity developer and you wish to learn how to write C# scripts and code by creating games, then this book is for you.
What You Will Learn
- Understand the fundamentals of variables, methods, and code syntax in C#
- Get to know about techniques to turn your game idea into working project
- Use loops and collections efficiently in Unity to reduce the amount of code
- Develop a game using the object-oriented programming principles
- Generate infinite levels for your game
- Create and code a good-looking functional UI system for your game
- Publish and share your game with users
In Detail
Unity is a cross-platform game engine that is used to develop 2D and 3D video games. Unity 5 is the latest version, released in March 2015, and adds a real-time global illumination to the games, and its powerful new features help to improve a game’s efficiency.
This book will get you started with programming behaviors in C# so you can create 2D games in Unity. You will begin by installing Unity and learning about its features, followed by creating a C# script. We will then deal with topics such as unity scripting for you to understand how codes work so you can create and use C# variables and methods. Moving forward, you will find out how to create, store, and retrieve data from collection of objects.
You will also develop an understanding of loops and their use, and you’ll perform object-oriented programming. This will help you to turn your idea into a ready-to-code project and set up a Unity project for production. Finally, you will discover how to create the GameManager class to manage the game play loop, generate game levels, and develop a simple UI for the game.
By the end of this book, you will have mastered the art of applying C# in Unity.
Style and approach
This is a step-by-step guide to developing a game from scratch by applying the fundamentals of C# and Unity scripting.
Related to Learning C# by Developing Games with Unity 5.x - Second Edition
Related ebooks
Learning C++ by Creating Games with UE4 Rating: 3 out of 5 stars3/5Unity from Zero to Proficiency (Advanced): Unity from Zero to Proficiency, #4 Rating: 0 out of 5 stars0 ratingsUnity from Proficiency to Mastery (C# Programming): Unity 5 from Proficiency to Mastery, #2 Rating: 0 out of 5 stars0 ratingsUnity from Zero to Proficiency (Beginner): Unity from Zero to Proficiency, #2 Rating: 5 out of 5 stars5/5Unity from Zero to Proficiency (Proficient): Unity from Zero to Proficiency, #5 Rating: 5 out of 5 stars5/5Unity from Zero to Proficiency (Foundations) Fifth Edition: Unity from Zero to Proficiency, #1 Rating: 5 out of 5 stars5/5A Beginner's Guide to 2D Shooter Games: Beginners' Guides, #2 Rating: 0 out of 5 stars0 ratingsUnity from Zero to Proficiency (Intermediate): Unity from Zero to Proficiency, #3 Rating: 2 out of 5 stars2/5Unity from Proficiency to Mastery (Artificial Intelligence): Unity from Proficiency to Mastery, #1 Rating: 0 out of 5 stars0 ratingsMastering Unity Scripting Rating: 0 out of 5 stars0 ratingsBuilding a Game with Unity and Blender Rating: 0 out of 5 stars0 ratingsUnity Multiplayer Games Rating: 5 out of 5 stars5/5Functional C# Rating: 5 out of 5 stars5/5Unreal Engine 4 Game Development Essentials Rating: 4 out of 5 stars4/5Unity Game Development Blueprints Rating: 0 out of 5 stars0 ratingsMastering SFML Game Development Rating: 0 out of 5 stars0 ratingsGetting Started with 3D Animation in Unity: Getting Started, #1 Rating: 0 out of 5 stars0 ratingsA Quick Guide to c# with Unity: Quick Guides, #1 Rating: 5 out of 5 stars5/5Getting Started with Unity 5 Rating: 5 out of 5 stars5/5Blueprints Visual Scripting for Unreal Engine Rating: 0 out of 5 stars0 ratings3D Game Design with Unreal Engine 4 and Blender Rating: 0 out of 5 stars0 ratingsUnity 5.x By Example Rating: 0 out of 5 stars0 ratingsAndroid Game Programming by Example Rating: 0 out of 5 stars0 ratingsProcedural Content Generation for Unity Game Development Rating: 0 out of 5 stars0 ratingsSFML Blueprints Rating: 0 out of 5 stars0 ratingsLearning Java by Building Android Games Rating: 0 out of 5 stars0 ratingsUnreal Engine Game Development Cookbook Rating: 0 out of 5 stars0 ratingsOpenGL Game Development By Example Rating: 0 out of 5 stars0 ratingsMastering Unreal Engine 4.X Rating: 0 out of 5 stars0 ratingsSFML Game Development By Example Rating: 0 out of 5 stars0 ratings
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Hacking: Ultimate Beginner's Guide for Computer Hacking in 2018 and Beyond: Hacking in 2018, #1 Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5OneNote: The Ultimate Guide on How to Use Microsoft OneNote for Getting Things Done Rating: 1 out of 5 stars1/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5C# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsLearn SQL in 24 Hours Rating: 5 out of 5 stars5/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsPython: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5TensorFlow in 1 Day: Make your own Neural Network Rating: 4 out of 5 stars4/5Mastering Windows PowerShell Scripting Rating: 4 out of 5 stars4/5Raspberry Pi: Beginner's Guide - Learn Raspberry Pi in Easy Steps Rating: 2 out of 5 stars2/5
Reviews for Learning C# by Developing Games with Unity 5.x - Second Edition
4 ratings1 review
- Rating: 5 out of 5 stars5/5Nice Book .And thank u for making this one :>
Book preview
Learning C# by Developing Games with Unity 5.x - Second Edition - Lukosek Greg
Table of Contents
Learning C# by Developing Games with Unity 5.x Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Discovering Your Hidden Scripting Skills and Getting Your Environment Ready
Prerequisite knowledge to use this book
Dealing with scriptphobia
Downloading Unity
Obtaining a free license
Teaching behavior to GameObjects
Using Unity's documentation
Do I need to know all that?
C# documentation – where to find it? Do I need it at all?
The Unity community – asking others for help
Working with C# script files
Lots of files can create a mess
Why does my Project tab look different?
Creating a C# script file
Introducing the MonoDevelop code editor
Syncing C# files between MonoDevelop and Unity
Opening LearningScript in MonoDevelop
The namespace – highlighted in blue
The class definition – highlighted in green
Watching for possible gotchas while creating script files in Unity
Fixing synchronization if it isn't working properly
Adding our script to GameObject
Instance? What is it?
Summary
2. Introducing the Building Blocks for Unity Scripts
Understanding what a variable is and what it does
Naming a variable
A variable name is just a substitute for a value
Creating a variable and seeing how it works
Declaration
Assignment
Click on Play!
Changing variables
Watching for a possible gotcha when using public variables
What is a method?
Using the term method
instead of function
Method names are substitutes, too
Introducing the class
Inheritance
The Start(), Update(), and Awake() methods and the execution order
Components that communicate using dot syntax
What's with the dots?
Making decisions in code
Using the NOT operator to change the condition
Checking many conditions in an if statement
Using else if to make complex decisions
Making decisions based on user input
Paper and pencil are powerful tools
Summary
3. Getting into the Details of Variables
Writing C# statements properly
Understanding component properties in Unity's Inspector
Variables become component properties
Unity changes script and variable names slightly
Changing a property's value in the Inspector panel
Displaying public variables in the Inspector panel
Private variables
Naming your variables properly
Beginning variable names with lowercase
Using multiword variable names
Declaring a variable and its type
The most common built-in variable types
Assigning values while declaring a variable
Where you declare a variable is important
Variable scope – determining where a variable can be used
Summary
4. Getting into the Details of Methods
Using methods in a script
Naming methods properly
Beginning method names with an uppercase letter
Using multiword names for a method
Parentheses are part of the method's name
Defining a method the right way
The minimum requirements for defining a method
Understanding parentheses – why are they there?
Specifying a method's parameters
How many parameters can a method have?
Returning a value from a method
Returning the value
Example
Summary
5. Lists, Arrays, and Dictionaries
What is an array?
Declaring an array
Storing items in the List
Common operations with Lists
List
Retrieving the data from the Array or List
Checking the size
ArrayList
Dictionaries
Accessing values
How do I know what's inside my Hashtable?
Summary
6. Loops
Introduction to loops
The foreach loop
The for loop
An example
The while loop
while versus for loops
Loops in statements
Modulo
Searching for data inside an array
Breaking the loop
Summary
7. Object, a Container with Variables and Methods
Working with objects is a class act
Few facts
Example
Instantiating an object
Bored yet?
Using methods with objects
Custom constructors
Overloading
Summary
8. Let's Make a Game! – From Idea to Development
Your first game – avoiding the trap of the never-ending concept
The idea
Game mechanics and core components
Breaking a complex idea into smaller parts
Jake on the mysterious planet – the feature list
Procedural level generation
An animated 2D character
Physics
Mouse and touch controls
Collectables and obstacles
Scoring
UI – the user interface
Target platform and resolution
Target screen resolution
Summary
9. Starting Your First Game
Setting up a new Unity project for our game
Backup
Keeping your project clean
Preparing the player prefab
Rigidbody2D
CircleCollider2D
PlayerController
User input
Jump
Animator
Running
Code
PlayerController.cs
Summary
10. Writing GameManager
Gameplay loops
Singleton class
Starting the game
Setting up input keys
Using triggers
Restarting the game
Setting up the player starting position
Code in this chapter
Summary
11. The Game Level
Generating levels versus designed levels
Creating a level chunk
Planning the LevelGenerator class
Writing LevelGenerator
Commenting on your code
Creating a copy of the level piece
Instantiating
Vector3
Testing LevelGenerator
Extending the level
The code used in this chapter
Summary
12. The User Interface
Introducting the Unity UI
Views
Constructing the view UI – how to keep things clean
Target screen resolution
Recognizing events
Buttons
A simple button
Image
The Button component
Interaction
The Button action
Hiding and showing the Canvas
Reference exceptions
GameView
Game Over
The code in this chapter
Summary
13. Collectables — What Next?
Collectables
The coin prefab
The Collectable class
High score and persisting data
The Update function and UI values
What next?
The code in this chapter
Summary
Index
Learning C# by Developing Games with Unity 5.x Second Edition
Learning C# by Developing Games with Unity 5.x Second Edition
Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: September 2013
Second edition: March 2016
Production reference: 1220316
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-759-6
www.packtpub.com
Credits
Author
Greg Lukosek
Terry Norton
Reviewer
Karl Henkel
Commissioning Editor
Ashwin Nair
Acquisition Editor
Vinay Argekar
Content Development Editor
Deepti Thore
Technical Editor
Mohita Vyas
Copy Editor
Vikrant Phadke
Project Coordinator
Shweta H Birwatkar
Proofreader
Safis Editing
Indexer
Mariammal Chettiyar
Graphics
Disha Haria
Production Coordinator
Nilesh Mohite
Cover Work
Nilesh Mohite
About the Author
Greg Lukosek was born and raised in the Upper Silesia region of Poland. When he was about 8 years old, his amazing parents bought him and his brother a Commodore C64. That was when his love of programming started. He would spend hours writing simple basic code, and when he couldn't write it on the computer directly, he used a notepad.
Greg completed his mechanical engineering diploma at ZSTiO Meritum—Siemianowice Slaskie, Poland. He has learned all his programming skills through determination and hard work at home.
Greg met the love of his life, Kasia, in 2003, which changed his life forever. They both moved to London in search of adventure and decided to stay there.
He started work as a 3D artist and drifted away from programming for some years. Deep inside, he still felt the urge to come back to game programming. During his career as a 3D artist, he discovered Unity and adopted it for an interactive visualizations project. At that very moment, he started programming again.
His love for programming overcomes his love for 3D graphics. Greg ditched his 3D artist career and came back to writing code professionally. He is now doing what he really wanted to do since he was 8 years old—developing games.
These days, Greg lives in a little town called Sandy in the UK with Kasia and their son, Adam.
I want to thank my loving wife, Kasia, for all her love and support. Without her, writing this book would be simply impossible. I also want to thank my loving parents, Ela and Marek, and brother, Artur, for always believing in me and giving me exceptional support when I needed it.
Then, I want to thank our son, Adam, for being an awesome child. I hope you will also do what you love in your life.
About the Reviewer
Karl Henkel is a software developer with a strong background in Unity3d. He is the author of several popular editor extensions in the Unity Asset Store. In addition to game development, he has also worked extensively on visual programming software for musicians and VJs.
www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt'ssw online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
Hello, future game developers! If you are reading this book, you are probably a curious person trying to learn more about a great game engine—Unity—and specifically, programming in C#. This book will take you on a learning journey. We will go through it together, beginning with the fundamentals of programming and finishing with a functional 2D platform game.
What this book covers
Chapter 1, Discovering Your Hidden Scripting Skills and Getting Your Environment Ready, puts you at ease with writing scripts for Unity.
Chapter 2, Introducing the Building Blocks for Unity Scripts, helps you develop the skill of writing your first executable code.
Chapter 3, Getting into the Details of Variables, teaches you about creating and using C# variables, followed editing them in Unity Inspector.
Chapter 4, Getting into the Details of Methods, helps you learn more in detail about methods and how to use them to understand the importance of code blocks and the variables used in them.
Chapter 5, Lists, Arrays, and Dictionaries, introduces slightly more complex ideas of handling, lists, arrays, and dictionaries, which allow you to store many values at once.
Chapter 6, Conditions and Looping, helps you learn how to ask
Unity to loop through a section of code and do something useful.
Chapter 7, Objects, a Containers with Variables and Methods, dives into the subjects of organizing your code and object-oriented programming.
Chapter 8, Let's Make a Game! – From Idea to Development, shows you how to turn an idea into a ready-to-code project and how to break down complex mechanics into pieces.
Chapter 9, Starting Your First Game, helps us transform an idea into a real Unity project.
Chapter 10, Writing GameManager, gets you acquainted with the basics of the singleton approach and also helps you work through the gameplay loop.
Chapter 11, The Game Level, helps you learn how to create reusable pieces of a level and also how to populate them to create the illusion of an endlessly running game.
Chapter 12, The User Interface, explains how to construct and implement the user interface in our game.
Chapter 13, Collectables — What Next?, focuses on collectables and storing some data between Unity sessions.
What you need for this book
You will definitely need a computer—PC, Mac, or any machine that supports Unity editor installation.
The complete Unity system requirements can be found at this link:
https://unity3d.com/unity/system-requirements
Who this book is for
The book is targeted at beginner-level Unity developers with no prior programming experience. If you are a Unity developer and wish to create games by learning how to write C# scripts or code, then this book is for you.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Add the Collectable script to your coin prefab.
A block of code is set as follows:
using UnityEngine;
using System.Collections;
public class LeaveTrigger : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other) {
LevelGenerator.instance.AddPiece();
LevelGenerator.instance.RemoveOldestPiece();
}
}
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: When you are ready, click on Play in Unity.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files