39,59 €
Develop your first interactive 2D platformer game by learning the fundamentals of C#
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.
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.
This is a step-by-step guide to developing a game from scratch by applying the fundamentals of C# and Unity scripting.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 234
Veröffentlichungsjahr: 2016
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
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
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.
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.
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 <[email protected]> for more details.
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.
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.
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.
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
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.
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:
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."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 <[email protected]>, 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.
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.
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 e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningCbyDevelopingGameswithUnity5x_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Computer programming is viewed by the average person as requiring long periods of training to learn skills that are totally foreign, and darn near impossible to understand. The word geek is often used to describe a person who can write computer code. The perception is that learning to write code takes great technical skills that are just so hard to learn. This perception is totally unwarranted. You already have the skills needed but don't realize it. Together, we will crush this false perception that you may have of yourself by refocusing, one step at a time, on the knowledge that you already possess to write code and develop an awesome game from scratch.
In this chapter, we will cover the following topics:
Let's begin our journey by eliminating any anxiety about writing scripts for Unity and become familiar with our scripting environment.
Great news if you are a beginner in scripting! This book is for those with absolutely no knowledge of programming. It is devoted to teaching the basics of C# with Unity.
However, some knowledge of Unity's operation is required. I will only be covering the parts of the Unity interface that are related to writing C# code. I am assuming that you know your way around Unity's interface. I will help you, however, to prepare the Unity layout for efficient scripting.
You've got Unity up and running, studied the interface, and added some GameObjects to the scene. Now you're ready to have those GameObjects move around, listen, speak, pick up other objects, shoot the bad guys, or do anything else that you can dream of. So you click on Play, and nothing happens. Well, darn it all anyway!
You've just learned a big lesson; all those fantastic, highly detailed GameObjects are dumber than a hammer. They don't know anything, and they surely don't know how to do anything.
So, you proceed to read the Unity Forums, study some scripting tutorials, and maybe even copy and paste some scripts to get some action going when you click on Play. That's great, but then you realize that you don't understand anything in the scripts you've copied. Sure, you probably recognize the words, but you fail to understand what those words do or mean in a script.
You look at the code, your palms get sweaty, and you think to yourself, "I'll never be able to write scripts!" Perhaps, you have scriptphobia—a fear of not being able to write instructions (I made that up). Is that what you have?
The fear that you cannot write down instructions in a coherent manner? You may believe you have this affliction, but you don't. You only think you do.
The basics of writing code are quite simple. In fact, you do things everyday that are just like steps executed in a script. For example, do you know how to interact with other people? How to operate a computer? Do you fret so much about making a baloney sandwich that you have to go to an online forum and ask how to do it?
Of course you don't. In fact, you know these things as every day routines or maybe habits. Think about this for a moment: do you have to consciously think about these routines that you do everyday? Probably not. After you do them over and over, they become automatic.
The point is that you do things everyday following sequences of steps. Who created these steps that you follow? More than likely, you did, which means that you've been scripting your whole life.
You just never had to write down the steps for your daily routines on a piece of paper before you did them. You could write the steps down if you really wanted to, but it takes too much time and there's no need of it; however, you do in fact know how to. Well, guess what? To write scripts, you only have to make one small change—start writing down the steps, not for yourself but for the world that you're creating in Unity.
So as you see, you are already familiar with the concept of dealing with scripts. Most beginners of Unity easily learn their way around the Unity interface, how to add assets, and working in the Scene and Hierarchy windows. Their primary fear, and roadblock, is their false belief that scripting is too hard to learn.
Relax! You now have this book. I am going to get really basic in the early chapters. Call them baby steps if you want, but you will see that scripting for Unity is similar to doing things that you are already doing everyday. I'm sure you will have many Ah-Ha moments as you learn and overcome your unjustified fears and beliefs.
You have probably already installed and activated Unity. Where you should look for the latest Unity version and license might be obvious. However, I've noticed lots of questions online about where you can get Unity for free, and so I decided to cover this subject. If you feel that this step is obsolete for you, skip this part.
The best place to download your Unity copy from is, of course, Unity's official website: http://unity3d.com/unity/download.
In this book, we will be covering Unity Version 5.0 and higher. We need to download the latest version of Unity and install it with all components ticked. It's a good idea to install Unity with the example project. The Unity Example project (the Angry Bots game) is there for us to play with, experiment, and learn.
The easiest way to obtain a Unity license is by simply launching Unity for the first time. The following steps will guide you to do so:
You are now all set with the latest version of Unity and a free license!
You have Unity because you want to make a game or something interactive. You've filled your game with dumb GameObjects. What you have to do now is be their teacher. You have to teach them everything that they need to know to live in this world of make-believe. This is the part where you have to write down instructions so that your GameObjects can be smarter.
Here's a quote from the Unity Manual:
The behavior of GameObjects is controlled by the Components that are attached to them... Unity allows you to create your own Components using scripts.
Notice the word behavior. It reminds me of a parent teaching a child proper behavior. This is exactly what we are going to do when we write scripts for our GameObjects; we'll teach them the behaviors we want them to have. The best part is that Unity has provided a long list of all the behaviors that we can give to our GameObjects. This list of behaviors is documented in the Scripting Reference.
This means that we can pick and choose anything that we want a GameObject to do from this list of behaviors. Unity has done all the hard work of programming all of these behaviors for you. All we need to do is use some code to tie into these behaviors. Did you catch that? Unity has already created the behaviors; all that we have to do is supply a bit of C# code to apply these behaviors to our GameObjects. Now, how difficult can it really be since Unity has already done most of the programming?
When we begin writing scripts, we will be looking at Unity's documentation quite often, so it's beneficial to know how to access the information that we need. For an overview of a topic, we'll use the Reference Manual, and for specific coding details and examples, we'll use the Scripting Reference.
There are a number of ways to access the Unity documentation:
Let's open Scripting Reference now and search for a GameObject. This is the place where we can find scripting documentation, answers to our questions, and a lot of example code. You might feel a bit lost right now, but don't worry; this is quite normal. The Unity documentation is really easy to use. For fastest access to relevant information, use Search scripting... in the top-right corner, as shown here:
Actually, no. The whole reason Scripting Reference exists is so that we can look for information as we need it. This will actually make us remember the code that we write over and over, just like our other daily routines and habits. It is a very good idea to take a brief look through the most common Unity objects, such as:
Another resource that we will be using is Microsoft's C# scripting documentation. We can access it at https://msdn.microsoft.com/en-us/library/67ef8sbd.aspx.
Let's not worry about it too much at the moment. We agreed to take baby steps, so bookmark this link in your web browser for now.
You are planning to become a game developer, or are using Unity for other interactive projects. During production, at some point, you will definitely need help from other developers. Unity has a very dedicated community of developers who are always keen to help each other.
When we encounter some hurdles, why not ask others? In most cases, there is someone like you out there with similar issues that have been resolved. A good place to talk about issues in your project is Unity Forums. Go ahead and create a forum account now! Don't be shy; say "hello" to others! Unity Forums are also the perfect place to read announcements about upcoming updates.
Use Unity Forums to read about others' work, share your work, and connect with other developers, at http://forum.unity3d.com/.
Use Unity Answers to ask specific questions about issues that you have encountered. Remember to be very specific, try to describe the problem in detail, and don't ask general questions (for example, "Why is my GameObject not moving?"). Instead, ask specifically, "GameObject not moving when adding a rigid body force" and then describe the details. Posting your code under the question is also a very good idea.
