Unity is a popular game engine used by both by AAA studios and indie game developers alike. This book will introduce you how to create games with Unity whether you have some game development experience or you are a complete beginner.
Unity Games by Tutorials Unity Games by Tutorials Mike Berg, Sean Duffy, Brian Moakley, Eric Van de Kerckhove, and Anthony Uccello Copyright ©2017 Razeware LLC Notice of Rights All rights reserved No part of this book or corresponding materials (such as text, images, or source code) may be reproduced or distributed by any means without prior written permission of the copyright owner Notice of Liability This book and all corresponding materials (such as source code) are provided on an “as is” basis, without warranty of any kind, express of implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in action of contract, tort or otherwise, arising from, out of or in connection with the software or the use of other dealing in the software Trademarks All trademarks and registered trademarks appearing in this book are the property of their own respective owners raywenderlich.com Unity Games by Tutorials Dedications "To the experimenters, learners and creators To those taking on the monumental task of making games, and learning to create art on top of that To the creation of something no one has seen before." — Mike Berg "To my wife Carmen, and my son Braeden, who provide me inspiration every day to achieve more than I would ever think possible." — Sean Duffy "To Lizzie, Fiora, and Rowen — these words exist only from your sacrifice and blessings My others find joy in them as I find joy in you." — Brian Moakley "To my loving girlfriend who has always been patient with me and respects the time I spend making and playing games." — Eric Van de Kerckhove "To my loving wife Carrie Oglestone, and our two dogs, Bowser and Daisy, and our three cats, Jack, Ripper, and Boo." — Anthony Uccello raywenderlich.com Unity Games by Tutorials About the authors Mike Berg is a full-time game artist who is fortunate enough to work with many indie game developers from all over the world When he's not manipulating pixel colors, he loves to eat good food, spend time with his family, play games and be happy You can check out his work at www.weheartgames.com Sean Duffy is a software engineer by day, and hobbyist game and tools developer by night He loves working with Unity, and is also a Unity Asset Store developer with a special focus on 2D tools to help other game developers Some of Sean's more popular Unity Assets include his 2D Shooter Bullet and Weapon System and 2D Homing Missiles assets You can find Sean on Twitter at @shogan85 Brian Moakley leads the Unity team at raywenderlich.com and also produces video tutorials on iOS, Unity, and various other topics When not writing or coding, Brian enjoys story driven first person shooters, reading genre fiction, and epic board game sessions with friends Eric Van de Kerckhove is a belgian hobbyist game dev and has been so for more than 10 years He started with DarkBasic, RPG Maker, Game Maker & XNA and now he makes games using Unity Eric also takes interest in 3D modelling, vector art and playing video games Anthony Uccello Anthony Uccello is a hardcore gamer and has been playing games since the Atari The only thing he loves more than playing games is making them with Unity He has contributed to published video games on both iOS and Android Anthony is a Senior Consultant at Infusion and is working on his own dungeon-crawlingtactical-RPG video game during his off hours AnthonyUccello.com raywenderlich.com Unity Games by Tutorials About the editors Adrian Strahan is a tech editor of this book He is a freelance iOS developer and Project Manager living in the South West of England He's worked on iPhone and iPad apps since 2010 (iOS3) and specializes in mobile- and web-based application development Mitch Allen is a tech editor of this book Mitch is an indie developer, maker and tech writer You can find his games on iTunes and his modules on npmjs mitchallen.com Chris Belanger is an editor of this book Chris Belanger is the Book Team Lead and Lead Editor for raywenderlich.com If there are words to wrangle or a paragraph to ponder, he’s on the case When he kicks back, you can usually find Chris with guitar in hand, looking for the nearest beach, or exploring the lakes and rivers in his part of the world in a canoe Wendy Lincoln is an editor of this book She is a full-time project manager (PMP, actually) specializing in IT marketing and content development She has an unusual background that involves a culinary degree, cooking show, writing and activism Occasionally, she logs off help her husband with home improvement projects or enjoy beach life Brian Moakley is a final pass editor of this book Brian leads the Unity team at raywenderlich.com and also produces video tutorials on iOS, Unity, and various other topics When not writing or coding, Brian enjoys story driven first person shooters, reading genre fiction, and epic board game sessions with friends Ray Wenderlich is a final pass editor of this book Ray is part of a great team - the raywenderlich.com team, a group of over 100 developers and editors from across the world He and the rest of the team are passionate both about making apps and teaching others the techniques to make them When Ray’s not programming, he’s probably playing video games, role playing games, or board games raywenderlich.com Unity Games by Tutorials About the artists Mike Berg made all of the 3D models, animations, and textures for this book He is a full-time game artist who is fortunate enough to work with many indie game developers from all over the world When he's not manipulating pixel colors, he loves to eat good food, spend time with his family, play games and be happy You can check out his work at: www.weheartgames.com Vinnie Prabhu created all of the music and sounds for the games in this book Vinnie is a music composer/software engineer from Northern Virginia who has done music and sound work for concerts, plays and video games He's also a staff member on OverClocked ReMix, an online community for music and video game fans You can find Vinnie on Twitter as @palpablevt raywenderlich.com Unity Games by Tutorials Table of Contents: Overview Introduction 17 Section I: Getting Started 24 Chapter 1: Hello Unity 25 Chapter 2: GameObjects 50 Chapter 3: Components 72 Chapter 4: Physics 96 Chapter 5: Managers and Pathfinding 126 Chapter 6: Animation 153 Chapter 7: Sound 183 Chapter 8: Finishing Touches 210 Section II: First-Person Shooters 239 Chapter 9: The Player and Environment 240 Chapter 10: Adding Enemies 268 Chapter 11: Introducing the UI 295 Section III: 2D Platformers 324 Chapter 12: Beginning Unity 2D 325 Chapter 13: More Unity 2D 352 Chapter 14: Saving Data 380 Section IV: Blender 409 Chapter 15: Modeling in Blender 410 raywenderlich.com Unity Games by Tutorials Chapter 16: Texturing with Blender 436 Chapter 17: Animating in Blender 460 Section V: Tower Defense Games 491 Chapter 18: Making A Tower Defense Game 492 Chapter 19: Making Towers 522 Chapter 20: Virtual Reality 558 Chapter 21: Publishing Your Game 587 Section VI: Appendices 603 Chapter 22: C# Crash Course 604 Chapter 23: Unity API 618 Chapter 24: Code Editors 632 Conclusion 650 raywenderlich.com Unity Games by Tutorials Table of Contents: Extended Introduction 17 Why Unity? 18 Unity vs Apple Game Frameworks 19 What you need 20 Who this book is for 20 How to use this book 21 Book source code and forums 21 Book updates 22 License 22 Acknowledgments 23 Section I: Getting Started 24 Chapter 1: Hello Unity 25 Installing and running Unity 28 Learning the interface 32 Organizing your assets 36 Importing Assets 38 Add models to the Scene view 42 Adding the hero 46 Where to go from here? 49 Chapter 2: GameObjects 50 Introducing GameObjects 50 Creating a prefab 56 Creating spawn points 68 Where to go from here? 71 Chapter 3: Components 72 Getting started 73 Introducing scripting 77 Creating your first script 79 Managing Input 80 raywenderlich.com Unity Games by Tutorials Camera movement 86 Adding gunplay 89 Where to go from here? 95 Chapter 4: Physics 96 Getting started 96 Destroying old objects 107 Collisions and layers 109 Joints 112 Raycasting 121 Where to go from here? 124 Chapter 5: Managers and Pathfinding 126 Introducing the GameManager 126 Pathfinding in Unity 136 Final touches 149 Where to go from here? 152 Chapter 6: Animation 153 Getting started 154 The animation window 154 Introducing keyframe animations 155 Your first animation 156 Animation states 160 Animation state transitions 165 Animation state transition conditions 167 Triggering animations in code 170 Animating models 172 Imported animations 175 Animating the space marine 179 Where to go from here? 182 Chapter 7: Sound 183 Getting started 183 Playing background music 185 raywenderlich.com 10 Unity Games by Tutorials Chapter 24: Code Editors This is the current target of the IDE which should be Unity Editor When debugging, you can also set this to a game in progress — more on this later This section contains all the files in your current assembly It provides a nice way of switching files without leaving the editor This is the code editors and where you’ll spend the majority of your time I often use this as my only view This view is used for debugging scripts in real-time This view contains a bunch of utilities to assist with the writing of your code For instance, the Toolbox has boilerplate code that you can copy into your project Some views will pop-out then disappear, whereas others will remain fixed in place You can customize this behavior from the view itself Each view contains two buttons in the upper-right corner Pressing the square will either keep the view in place or make it visible for the limited time you need it The x will remove it entirely If you wish to recover a view, you can display it from the View menu Spaces or tabs Developers tend to either use spaces or tabs to indent their code As you probably know, which one is best can be a rather contentious issue MonoDevelop doesn’t care; in fact, it’s easy to change this setting Open the MonoDevelop preferences (Tools\Options on Windows and MonoDevelop\Preferences on Mac) You’ll see a window with a ton of configuration options Look for the section called Source Code, expand Code Formatting and select C# source code raywenderlich.com 636 Unity Games by Tutorials Chapter 24: Code Editors The Whitespace section contains all the options needed to match your preferences Keep in mind that these settings only affect new projects versus your current projects For this reason, it’s a good idea to set up the editor first before you start using it MonoDevelop also has the concept of policies, which are simply sets of predefined behaviors For instance, if you prefer spacing to match K&R Style, you can select the K&R policy from the Policy dropdown These changes only affect C# files Under the Code Formatting section, you’ll notice other file types such as Text file and XML file If you want those files to behave in a similar manner, you’ll have to configure them as well Braces Braces, like tabs and spaces, are another source of controversy between developers Everyone has their preferences, and it’s terribly obnoxious when an IDE forces the raywenderlich.com 637 Unity Games by Tutorials Chapter 24: Code Editors matter Thankfully, MonoDevelop allows you to reconfigure how braces are formatted as well To configure your braces, select the C# Format tab in the C# Source code page You’ll then see a panel with some sample code The code window shows the current brace style To change the styling, click the Edit button to reveal a list of options In here, you can configure all aspects of C# formatting From the Category option, select Braces At this point, you can configure how braces will behave throughout MonoDevelop If you were particularly mischievous, you could reconfigure a friend’s environment according to your preferences the same way raywenderlich.com 638 Unity Games by Tutorials Chapter 24: Code Editors Project templates You’ll quickly discover that even though you’ve configured your MonoDevelop settings, new C# files created inside of Unity won’t reflect these changes This is because Unity uses templates to generate MonoBehaviour classes — yes, the International English spelling is correct syntax You have to modify the project templates so all new files will acquire them On Windows, you access them from C:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates On a Mac, you need to open the Applications folder in Finder, then right-click the Unity.app bundle and select Show Package Contents Inside the bundle, you can access the templates in Contents/ Resources/ScriptTemplates/ Only after that will your changes be applied to newly generated scripts inside of Unity Make sure to restart Unity after your changes Be advised that new versions of Unity may go ahead and overwrite your precious templates, so yourself a solid and keep a separate copy of them somewhere safe, perhaps even in a safe deposit box Debugging When working with Unity, the easiest way to diagnose bugs is to print a message to the console like so: Debug.Log("Hello!"); This is a basic way of approaching a problem that’s also known as caveman debugging While it’s useful to see certain values in the console, it fills your log with messages For repeating methods like Update(), finding the important messages is very much like searching for a needle in a haystack Thankfully, Unity comes with an integrated debugger that empowers you to solve problems in a more sophisticated manner raywenderlich.com 639 Unity Games by Tutorials Chapter 24: Code Editors To get started with debugging, you need to create a breakpoint A breakpoint is an indication to the debugger where the code should pause its execution In MonoDevelop, you specify a breakpoint by clicking the gutter on the left-hand side of the editor Doing so produces a red dot and highlights the selected line in red This won’t stop your code — yet You must start the debugger To that, press the play button, making sure the Unity Editor is the current target Once you start the debugger, it will attach itself to the Unity editor At this point, when you play your game, the editor will pause at the breakpoint, giving you an opportunity to inspect any variables You can this with the Locals view found in the debug area raywenderlich.com 640 Unity Games by Tutorials Chapter 24: Code Editors This view allows you to inspect variables in real-time without having to bother with writing log statements Of course, you can also move through your code, line by line Near the debugger play button, you’ll notice a series of controls These controls allow you to resume execution of the program, skip a line, or step in and out of a certain method As you develop games, you’ll discover that the debugger is indispensable Getting started with Visual Studio As mentioned before, Unity comes bundled with MonoDevelop While it does provide a consistent coding environment on all platforms, its quirks are bound to drive you to pulling your hair out — eventually Thankfully, on Windows, installing Visual Studio is easy You might be tempted to head over to Microsoft’s download center, but stop right there Unity requires additional software to integrate with Visual Studio It’s finicky like that The right way to get Visual Studio is by downloading it via the Unity installer If you deleted the installer, just download it again from Unity’s website When you start the installer, select the option, Microsoft Visual Studio Community 2015 raywenderlich.com 641 Unity Games by Tutorials Chapter 24: Code Editors You’ll be prompted to accept some EULAs, and then it’s a just a matter of sitting back and waiting for the IDE to install Unity will also configure all the additional tools that make it play nice with Unity The installation will take a while, but it’s worth the wait raywenderlich.com 642 Unity Games by Tutorials Chapter 24: Code Editors Getting used to Visual Studio Visual Studio can be intimidating, but it’s not so bad once you get to know it Like Unity, it’s composed of a series of views you can arrange into custom layouts You can save your layouts and reuse them for certain tasks and workflows Here’s a breakdown of the editor: This is your standard menubar and toolbar to assist with various tasks An important button is the Attach to Unity button, which you’ll use to start debugging This your code editor I tend to keep just this view open when working on projects, as it helps me avoid the distraction that comes from visual noise Some views will appear underneath the editor Typically, this is where you manage your debugger and learn of errors in your project The right-hand column provides another location for tools such as the Solution Explorer which allows you to not only see all your script files, but expand them to see all their methods and properties at a glance Like Unity, views can be added, removed and docked By clicking the View option from the menubar, you’ll see that you have a plethora of views at your disposal, complete with hotkeys to activate them without the hassle of using your mouse raywenderlich.com 643 Unity Games by Tutorials Chapter 24: Code Editors WTF is CR LF? When you first open a script in Unity, you may encounter a weird dialog that looks like the following: No warning is fun, never mind those warnings that make absolutely no sense This pesky warning relates to the line endings of the generated script files That’s right, the cause of the problem is the file itself Whoever created the file did it in a Unix-based system, whereas you’re using a Windows-based system Unix manages line endings differently than Windows, so this error is Visual Studio way of asking how to handle these mysterious line endings Simply click OK and Visual Studio will politely convert the line endings for you “But wait”, you say, “I get this even when I create a new file! What gives?” raywenderlich.com 644 Unity Games by Tutorials Chapter 24: Code Editors Unity creates new scripts based on templates, and those templates are the cause of the line ending issues To fix the issue, you must change the templates What is it with IDEs and their funky templates? First, open Visual Studio Click File\Open\File and then head over to the following location: C:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates This directory contains a list of templates that Unity uses to create your scripts For fixing the C# templates, open 81-C# Script-NewBehaviourScript.cs.txt Next, click File\Advanced Save Here you’ll see a familiar dialog Set the line endings to Windows (CR LF) and click OK Now you’ll no longer get that message When working with a source control program such as git, the Windows line endings will be stripped — don’t be surprised when you encounter the message again Braces and spaces If you ever want to start a fight at a developer conference, pick a packed table at lunch, declare “tabs for life”, then get out of there before the lasagna starts flying so you can livestream the fiasco Developers have their preferences and can be quasi-religious about them raywenderlich.com 645 Unity Games by Tutorials Chapter 24: Code Editors Thankfully, Visual Studio is amiable It won’t scold you for inserting tabs nor will it scoff at you for tapping the space bar To customize formatting, select Tools\Options When the window opens, you’ll see a ton of things to configure Thankfully, the options contain a search bar to make it easier to find the setting(s) you seek To change your indent style, you can find the options under Text Editor\C#\Tabs like the following: To change your brace style, you can find the options under Text Editor\C#\Formatting\New Lines like so: You can set up your braces by reviewing the options and checking the conditions for when the brace should be on a new line raywenderlich.com 646 Unity Games by Tutorials Chapter 24: Code Editors Keep in mind that any changes that you make to brace options in Visual Studio won’t be reflected in any new Unity script files This is because Unity creates new scripts based on — you guessed it — templates as covered in the previous section To change the styling, you’ll need to change the template files as outlined in the last section Restart Unity after making your changes These changes will only affect new scripts For existing scripts, you’ll have to change things manually Debugging Being a top-level IDE, Visual Studio also comes with a top-level debugger Debuggers allow you to pause your game in motion and inspect the state of the variables Note: This section matches the previous debugging section for MonoDevelop with the instructions for Visual Studio instead To get started with debugging, you first need to create a breakpoint A breakpoint is an indicator to the debugger that it should pause its execution at that point Just as you with MonoDevelop, you create a breakpoint by clicking on the gutter in the left-hand side of the editor Doing so will produce a red dot and highlight the line in red This won’t stop your code — yet To start the debugger, press the play button and make sure the Unity Editor is the current target Once you start the debugger, it will attach itself to the Unity editor When you play the game, the editor will pause at the breakpoint so that you can inspect any variables in your game You can this with the Autos view raywenderlich.com 647 Unity Games by Tutorials Chapter 24: Code Editors This view allows you to inspect your variables in real-time without writing bothersome log statements Of course, you can also move through your code line by line You’ll notice a series of controls near the debugger play button These controls allow you to resume execution of the program, skip a line, and step freely in and out of methods As you develop games, you’ll discover the debugger is an indispensable tool Expiration After 30 days, you may log in and get a rude awakening about how the evaluation period has ended Once you cross that threshold, there’s no turning back You won’t be able to use the software until you appease the makers — you must register it with your Microsoft account Have no fear! If you’re using the community edition, you still don’t have to pay to play All you need is create a free Microsoft account (or use your existing) and then answer some questions After that, it’s business as usual To register your copy of Visual Studio, simply go to Help\Register Product It’s better to it early in the process rather than waiting until the trial ends You know how Murphy’s law works, right? You’ll get that message at the worst possible time Doing it early means you won’t have worry about jumping through hoops when your internet has crashed, and you have a deadline staring you in the face :] Where to go from here? IDEs are meant to assist with your pursuit of being a faster and more productive coder If you find yourself changing your development habits to match the workflow of the editor, then you should reconsider the relationship and investigate alternatives Ultimately, choose what works best for you and your team Once you select your tool, make sure to keep learning about it; these programs are feature-rich and can take a raywenderlich.com 648 Unity Games by Tutorials Chapter 24: Code Editors while to master The more you understand your IDE, the less time you spend figuring out how the thing works and the more time you spend making amazing games! raywenderlich.com 649 C Conclusion We hope you’ve enjoyed this book as much as we enjoyed making it! Unity is an amazing platform for building games that look incredible and are a joy to play We can’t wait to see what you’ll produce on your own, now that you’re armed with all the information you covered in this book If you have any questions or comments as you continue to develop with Unity, please stop by our forums at http://www.raywenderlich.com/forums and share your thoughts We thank you sincerely for purchasing this book Your continued support is what makes the tutorials, books, videos, conferences and everything else we at raywenderlich.com possible — we truly appreciate it! Wishing you all the best, wherever your Unity gaming adventures take you, – Mike, Sean, Brian, Eric, and Anthony The Unity Games by Tutorials team raywenderlich.com 650 .. .Unity Games by Tutorials Unity Games by Tutorials Mike Berg, Sean Duffy, Brian Moakley, Eric Van de Kerckhove, and Anthony Uccello Copyright ©2017 Razeware LLC... programming, he’s probably playing video games, role playing games, or board games raywenderlich.com Unity Games by Tutorials About the artists Mike Berg made all of the 3D models, animations, and textures... include this attribution line somewhere inside your game: “Artwork/images/designs: from the Unity Games by Tutorials book, available at www.raywenderlich.com” • The source code included in Unity Games