Second Edition Create professional games with solid gameplay features and professional-grade workflow Alan Thorn Mastering Unity 2017 Game Development with C# BIRMINGHAM - MUMBAI Second Edition Copyright © 2017 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(s), 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: January 2017 Second edition: October 2017 Production reference: 1271017 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78847-983-7 www.packtpub.com Mastering Unity 2017 Game Development with C# Credits Author Alan Thorn Copy Editor Shaila Kusanale Reviewers Michael Miles Alessandro Mochi Project Coordinator Devanshi Doshi Commissioning Editor Amarabha Banerjee Proofreader Safis Editing Acquisition Editor Larissa Pinto Indexer Pratik Shirodkar Content Development Editor Onkar Wani Graphics Jason Monteiro Technical Editor Harshal Kadam Production Coordinator Arvindkumar Gupta About the Author Alan Thorn is a multidisciplinary game developer, author, and educator with 17 years of industry experience. He makes games for PC desktop, mobile, and VR. He founded Wax Lyrical Games and created the award-winning game Baron Wittard: Nemesis of Ragnarok , working as designer, programmer, and artist. He has written 23 technical books on game development and presented 19 video training courses. These cover gameplay programming, Unity development, and 3D modeling and animation. He has worked in game education as a senior lecturer for Teesside University, a lead teacher for Uppingham School, and a visiting lecturer for London South Bank University. Currently, he's the Head of Department for Games Design and Development at the National Film and Television School. This book would not have been possible if it hadn't been for the valuable help of many people. I would like to thank all my friends and family, and also the team at Packt Publishing. This includes Onkar Wani and Larissa Pinto. About the Reviewers Michael Miles is a manufacturing engineer working in the aerospace industry by day, and a Unity Game designer and C#, JavaScript, and Python developer the rest of the time. While he purchased his first computer in the early '80s, it was years later when he first got into programming, writing modifications for Doom during breaks at work. With gaming in general frowned upon, while working Michael put these skills to work, programming simulations for the various processes he used on the job. A few years later, he discovered Unity3D and Blender; using these applications, Michael creates interactive training and production-ready instruction tools for the assembly of parts for the aircraft his company builds. When not in front of a computer screen, he likes to play card games, board games with family and friends, and immerse himself in books from fantasy to theoretical physics. Thanks to my parents for always being there, supporting every decision I made, however unwise you thought it was at the time. Alessandro Mochi has been playing video games since the Amstrad and NES era, tackling all possible fields: PC, console, and mobile. They are his love, and designing them is his passion, used as a medium to transmit and evoke emotions. He gives a lot of importance to details while doing any work, and is well versed in project and team management, communication, and problem-solving skills. He is experienced in mechanical design, but is also quite good at programming (Unity, C#) and 3D modeling. With over 15 years of experience in IT and project management, he's currently pouring all of his heart and mind into the company he founded--Dapper Penguin Studios. Here, he tries to resurrect a lost genre in PC gaming--the industrial tycoon--with the flagship title Rise of Industry. Many studios have tried in recent years, and their failures serve as inspiration and fuel for his work, trying to give back to the gaming industry a fun, polished, and immortal experience. www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. 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.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com 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://www.packtpub.com/mapt Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career. 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 Customer Feedback Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788479831. If you'd like to join our team of regular reviewers, you can email us at customerreviews@packtpub.com . We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products! Table of Contents 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. Preparation and Asset Configuring Getting clear on design Target platforms Intended audience Genre Game mode Game objective Asset preparation Meshes - Work only with good topology Meshes - Minimize polygon count Meshes - Simulating bump details without geometry Meshes - Minimize UV seams Meshes - Export as FBX Meshes - Use meters scale (metric) Textures - Never use lossy compression Textures - Power of 2 sizes Textures - Alpha textures Asset importing for Dead Keys Importing textures Importing meshes Importing animations Importing audio Configuring materials Summary 2. Level Design and Structure Setting the scene with a skybox Level building - Modular construction sets Level building - Organization and structure Level design - Tips and tricks Objective and feedback Narrative Believability and convenience Atmosphere and aesthetic Simplicity and reuse Level lighting - Preparation Baked lighting Dynamic lighting Precomputed global illumination Getting started with lightmapping Baking lightmaps - Resolution and size Baking lightmaps - Details Light Probes Lighting FAQ Navigation mesh Occlusion Culling Creating a player camera Particle systems Music and audio Summary 3. Player Controls - Movement Player movement Zombie combat Creating player waypoints Animating the camera Configuring an animator graph Working with animation - creating the navigator Customizing and changing MonoDevelop Singletons Comments Connecting to the navigator component Comments Navigator GUI Input axes The canvas The button Coding button behavior Comments Creating player death Comments Summary 4. Player Controls - Typing and Health Word combat Creating a word list Using Visual Studio Code Creating a WordList class Comments Comments Matching words Comments The Typer object Progressing with the Typer class Comments Health and damage Comments Comments Damage and feedback Player score Comments Bonus items Comments Summary 5. Enemies and Artificial Intelligence Configuring the zombie character Getting started with the zombie Prefab Planning the zombie Artificial Intelligence Comments Developing state structure Comments Developing an NPC Animator Controller Developing the Idle state Comments Developing the Chase state Comments Developing the Attack state and more Comments Developing the Dead state Zombies and text input Comments Zombies and the Typer class Comments Comments Activating enemies and camera paths Working with Play mode Summary 6. Project Management and Version Control Project management Research, design, and work assessment Workload plan Task status Risk analysis Resources and skills needed Testing plan Applied project management using Trello Collaboration with cloud storage Version control using Git Getting started with Git and GitKraken Commits and branches Forward and backward with Git Configuring Unity for version control Reverting and discarding Branches and branching Conflicts and resolving Git and the web Pushing and pulling Cloning Summary 7. Persistent Data - Load and Save Game States Data serialization Player preferences - saving data Player preferences - loading data Player preferences - INI files Comments on iniParser.cs Saving data - XML files Comments Saving data - JSON files Comments Saving data - binary files Comments Saving data for Dead Keys Comments Summary 8. Performance, Optimization, Mobiles, and More Stats and performance Profiler and performance assessment Optimization tips and tricks Strings and comparisons Beware of functions in disguise Debug cleaning Optimizing build size Getting started with mobile development Moving forward with mobile development Building for Android Building for VR (Virtual Reality) Summary Preface Greetings and welcome to Mastering Unity 2017! This book begins from a beginner's knowledge of Unity, and it helps you develop that knowledge into mastery of a certain kind. Specifically, it develops a general, overarching mastery in which you’ll learn Unity like a seasoned indie developer, capable of turning your hand to pretty much any department and feature set within Unity. The following chapter outline explains, in more detail, the full range of features that we’ll see, but the central aim of this book is to make you versatile and powerful with Unity; capable of encountering a problem and being able to solve it in the language of Unity’s feature set. In this book, we’ll concentrate for the most part on a practical example; we’ll build a first-person combat game, across multiple chapters, and this will test your typing skills in more ways than one, so let’s go! What this book covers Chapter 1, Preparation and Asset Configuring , outlines the project we’ll focus on in the book. It specifies tips and tricks for importing assets optimally, configuring assets, and best-practice workflows for keeping your project organized. Chapter 2, Level Design and Structure , here, gets you started with designing and building the main game level inside Unity, taking a look at interesting level-design ideas as well as critically important practical considerations. Chapter 3, Player Controls - Movement , explores player controls, that is, how player input drives and controls the main game camera. Chapter 4, Player Controls – Typing and Health , says that every character that can take damage needs health, representing the total amount of damage a character may sustain. In this chapter, we’ll focus on creating a combat mechanic that damages enemies. Chapter 5, Enemies and Artificial Intelligence , informs that enemies need to behave intelligently and believably; this chapter looks at how to achieve that using AI. By using AI, enemies will move around the level, seeking the player, and will attack when in range. Chapter 6, Project Management and Version Control , looks at ways to optimize the game development workflow using Version Control software. This keeps a record of our project as it moves through all its iterations. Chapter 7, Persistent Data – Load and Save Game States , explains that players often want their in-game progress saved, allowing them to resume where they left off previously every time they start a new play session. This chapter covers the different saving methods available in Unity. Chapter 8, Performance, Optimization, Mobiles, and More , outlines a selection of related topics as the final chapter of this book. Specifically, it takes you through how to improve the performance of your games through optimization, how to prepare your games for mobile deployment, and how to prepare generally for VR development. What you need for this book To read this book effectively, and to complete the tasks within, you need only two things: first, the Unity 2017 software (which you can get for free from https://unity3d.com) and second, the determination to succeed! By using only these tools, you can learn to produce great games in Unity. Who this book is for If you are a Unity developer who now wants to develop and deploy interesting games by leveraging the new features of Unity 2017, then this is the book for you. Basic knowledge of C# programming is assumed. 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: To start again, create a new animator controller named animControl_Navigator A block of code is set as follows: public IEnumerator StateIdle() { //Run idle animation ThisAnimator.SetInteger("AnimState", (int) ActiveState); //While in idle state while(ActiveState == AISTATE.IDLE) { yield return null; } } 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: After installing the JDK, access the User Preferences dialog by choosing Edit | Preferences from the application menu, and select the External Tools tab. Warnings or important notes appear like this. 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 email 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.