39,59 €
With the increasing interest in game development, it's essential to design and implement a UI that reflects the game settings and shows the right information to the player. The Unity system is used to create complex and aesthetically pleasing user interfaces in order to give a professional look and feel to a game. Although the new Unity UI system is powerful and quite easy to use, by integrating it with C# scripts, it's possible to realize the potential of this system and bring an impressive UI to games.
This guide is an invaluable collection of recipes if you are planning to use Unity to develop a game. Starting with the basic concepts of the UI components, we’ll take you all the way through to creating complex interfaces by including animations and dynamics elements.
Based on real-world problems, these recipes will start by showing you how to make common UI elements such as counters and healthbars. You will then get a walkthrough of how to manage time using timers, and will learn how to format them. You will move on to decorating and animating the UI elements to vivify them and give them a professional touch. Furthermore, you will be guided into the 3D UI world and into HUD scripting. Finally, you will discover how to implement complex minimaps in the interface.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 404
Veröffentlichungsjahr: 2015
Copyright © 2015 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: December 2015
Production reference: 1181215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-582-2
www.packtpub.com
Cover image by Francesco Sapio and Lauren S. Ferro
Author
Francesco Sapio
Reviewers
Jack Donovan
Lauren S. Ferro
Commissioning Editor
Neil Alexander
Acquisition Editor
Nadeem Bagban
Content Development Editor
Mayur Pawanikar
Technical Editor
Deepti Tuscano
Copy Editor
Vikrant Phadke
Project Coordinator
Nidhi Joshi
Proofreader
Safis Editing
Indexer
Rekha Nair
Graphics
Jason Monteiro
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Francesco Sapio obtained his computer science and control engineering degree from the Sapienza University of Rome, Italy, with a couple of semesters in advance, scoring summa cum laude. Now he is studying a master's of science and engineering in artificial intelligence and robotics.
Besides this, he is a Unity3D expert and skilled game designer, as well as an experienced user of the major graphics programs.
Recently, he has been a reviewer of the book Unity Game Development Scripting, Packt Publishing.
Francesco is also a musician and composer, especially of soundtracks for short films and video games. For several years, he worked as an actor and dancer. He was a guest of honor at the theatre Brancaccio in Rome.
In addition, he is a very active person, having volunteered as a children's entertainer at the Associazione Culturale Torraccia in Rome. Also, he gives private lessons in mathematics and music to high-school and university students.
Finally, Francesco loves math, philosophy, logic, and puzzle solving, but most of all, creating video games — thanks to his passion for game designing and programming.
You can find him at https://linkedin.com/pub/francesco-sapio/b8/5b/365.
I'm deeply thankful to my parents for their infinite patience, enthusiasm and support for me throughout my life. Moreover, I'm thankful to the rest of my family, in particular to my grandparents, since they always encouraged me to do better in my life with the Latin expressions "Ad Maiora" and "Per aspera ad astra".
Besides this, I would like to thank my old Acquisition Editor for introducing me into this world and my current Content Developer for his kindness and patience.
Finally, a huge thanks to all the special people are around me who I love, in particular to my girlfriend; I'm grateful for all your help in everything.
Jack Donovan is a game developer and software engineer who has been working with the Unity3D engine since its third major release. He studied at Champlain College in Burlington, Vermont, USA, where he received a bachelor of science in game programming. Jack currently works at IrisVR, a virtual reality start-up in New York City, where he is developing software that allows architects to generate virtual reality experiences from their CAD models or blueprints. Before IrisVR, he worked on a small independent game team with fellow students. At that time, he also wrote the book OUYA Game Development By Example by Packt Publishing.
Lauren S. Ferro is a gamification consultant and designer with 10 years of experience designing interactive game and game-like applications across a variety of contexts. She has worked on, designed, and implemented strategies for a range of different purposes, from professional development to recommendation systems and educational games. She is an active researcher in the area of gamification, player profiling, and user-centred game design. Lauren runs workshops for both the general public and companies that focus on designing user-centered games and game-like applications. She is also the developer of the game design resource Gamicards (which will soon be available for purchase).
You can contact her on Twitter at @R3nza. Her website is www.laurensferro.com and her e-mail ID is <[email protected]>.
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.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's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Unity is a very flexible and high-performance game engine. It allows you to build small – to large-scale enterprise video games. It is designed to promote rapid development and clean, pragmatic design and lets you build high-performing, elegant games quickly. The main aim of this book is to teach you how to implement complete user interface systems that can interact with all other parts of your game. The book is structured in recipes, so the expert user can read them in any order that they like. But for those who are still learning, it can be read in order, as it guides you from the basic topics to advanced features that can be developed within the UI. Furthermore, the book often refers to the relation between the player and the UI. In fact, this is a very important factor to take into consideration in order to design and implement a UI that feels suitable and ultimately create a successful game.
Chapter 1, UI Essentials, gives us the basic tools needed to deal with the UI. These will be used throughout this book. Once learned, these tools provide the foundations for creating even more complex interfaces.
Chapter 2, Implementing Counters and Health Bars, provides different ways to implement the most often used UI systems: counters and health bars. They serve many purposes, such as keeping track of virtual currency and the number of lives that a player has.
Chapter 3, Implementing Timers, deals with the way time is used and represented in our game. Timers are a good way for players to experience flow throughout the game, and countdowns can indicate how much time is remaining to complete a task. Furthermore, they can change over time. Both timers and countdowns are effective methods of altering the dynamics of gameplay.
Chapter 4, Creating Panels for Menus, teaches you how to make different kinds of panel to create interactive menus. These menus contain elements such as sliders and draggable and resizable features.
Chapter 5, Decorating the UI, explains how it is possible to implement dynamic elements to decorate our UIs. In fact, these are a great way to give the player a feeling that the UI is dynamic and alive.
Chapter 6, Animating the UI, extends the concept of giving life to a UI from the previous chapter. In addition, this chapter provides methodologies that allow players to switch between different menus.
Chapter 7, Applying Runtime Customizations, examines the different levels of customization for the player that can be achieved during runtime, such as text filtering and slider lockers.
Chapter 8, Implementing Advance HUDs, helps you develop skills for taking information from the 3D world and then implementing it within your HUD elements. Such elements may include displaying the distance to an object, radar for detecting objects, as well as a subtitle shower system.
Chapter 9, Diving into 3D UIs, focuses on teaching some advanced features for placing UI elements within a 3D space by taking advantage of the z axis. Furthermore, it covers various scripts that enable our UI to interact with the 3D world in order to exchange inputs/outputs.
Chapter 10, Creating Minimaps, explores the many purposes that minimaps can serve, such as identifying locations of interest, objects, and even characters, such as locations of enemies and other players, which can be shown as icons on the minimap.
The only software you need is Unity 5.x, which can be downloaded from the official website:
However, it could be useful if you have some graphics programs for use throughout the recipes in this book for — rapid mock-ups and custom graphics.
Furthermore, Unity 5.x Pro is required to follow the last chapter of this book, since we will use render textures, which are available only with Unity Pro.
If you are a game developer with some experience with Unity and C# and want to create the best interactive experience fast and intuitively, then this book is for you. If you are an intermediate game developer or an expert, these recipes will help you bring out the power of the new UI Unity system.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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: "Since we don't need to set the initial variables, we can erase the Start() function."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written 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: "Clicking the Next button moves you to the next screen."
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 from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.
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 http://www.packtpub.com/sites/default/files/downloads/UnityUICookbook_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.
In this chapter, we will cover the following recipes:
This chapter explains how to use the essential tools for creating more complex interfaces. These tools include placing and scaling UI elements, using masks to shape figures, and making images and text scrollable along with sliders.
We start by creating a sprite with a border. It can be scaled up or down without distorting. Then, we will proceed with explaining how to make our UI resizable according to the resolution of our screen.
Later, we will introduce the most used UI component — the Image (Script). Then, you will learn how to implement more complex transformations, such as masking it or making it scrollable.
We will also see how to select buttons using the input from the keyboard by introducing how we can develop scripts that are able to interact with our UI.
Finally, we will look at the UI layout components that allow us to easily create and structure a very wide UI.
To get started with this chapter, we will need to have Unity 5 running, and we must create a new project. The project can be set in 3D or 2D, depending on which one better suits the game that we wish to make. However, if it is set in 2D, Unity will automatically import our images as sprites. Lastly, ensure that you have some nice images of your choice for use in the examples, such an ancient map.
To properly scale a 2D texture to the screen size, we may need to make it bordered. This allows us to force the resolution, but not scale all the parts of our image, in order to maintain the original appearance of the image. Buttons are often bordered because their appearance depends strongly on how corners are scaled, and we don't generally want them to scale.
Another way to add images to the project is by dragging and dropping them into the Project panel.
Sometimes, some components of our UI need to be scaled. However, not all of them can be scaled freely. Otherwise, it could look different from what we thought it should be. Therefore, bordered images are used to scale everything as it should be. Borders tell Unity how it has to scale the picture. When we drag the green points in the Sprite Editor, we are dividing the image into nine sections. Each of these sections is scaled differently. The central sections are scaled in both x and y directions (vertically and horizontally). The side sections are scaled in only one direction: vertically for the right/left sections and horizontally for the upper/lower sections). Finally, the corners do not scale at all. You can see these nine sections and the scales in the following image:
Let's consider an example to understand why a bordered sprite is important for the UI. Imagine that we have a button like the one in the preceding image and we have placed it on the screen. When the game runs on different devices, the resolutions will be different and Unity will scale our UI accordingly (see the next recipe for more information). Ideally, we want the button to look like the original one that we have designed as much as possible. This means, for instance, that we want to preserve the original curvatures of the corners, and therefore, we need to force them not to scale. This can be communicated to Unity using borders. In this way, the rest of the button can scale along with the screen size in order to fit it, but as a result, the button will look like the original one.
The next subtopic will show us how to slice the sprite without using all of the nine sections.
As you have learned so far, we can use the nine sections of the border to define the scaling setting of an image properly. But we are not constrained to use all of them. In fact, it is possible to segment the image into fewer sections. This is useful when we have some UI elements that are attached to the border of the screen. In fact, in this case, the image will scale differently according to only those sections that have been defined. To do this, we need to drag only some of the green points from the corners, instead of what we did in steps 5 and 6, where we dragged all them. By tweaking these, we can achieve different ways of scaling our UI, and the right one depends on how we want our game to look in different resolutions. For instance, we can create something similar to this:
One of the most difficult things to do in the older versions of Unity was scaling the UI (or GUI, the old Unity user interface system). In fact, the system was hard to learn, and most of the features had to be implemented by scripts, including scaling. However, in Unity 5, scaling the UI is much easier with the Canvas Scaler (Script) component. This component will take care of the scale of all UI elements that are contained in Canvas.
In the Unity UI system, Canvas is a special game object. This is because all the UI elements must be contained inside it. In fact, elements that are not in it will not be rendered. By default, Canvas comes with three components attached to it. One of these three is Canvas Scaler (Script). This component controls how all the UI elements that are contained in that specific Canvas will be scaled. By tweaking some of its properties, it is possible to achieve a scale setting that best suits our needs. In particular, we have set the Match slider, which allows us to proportionally crop the width and height of the view in order to adapt it to the resolution of the platform on which the game is running.
Since our UIs mostly consist of images, it's very important to learn how to handle them with the Image (Script) components in Unity. In fact, we will use them a lot in all the recipes of this book. In particular, here you can understand how to create a new image and properly place it in your UI.
UI components that are outside Canvas will not be drawn by Unity, so ensure that every UI component is always inside Canvas!
If they are not, we can drag and drop them onto the Canvas object so that they become children, and they appear again.
If our image is sliced, as we saw in the first recipe of this chapter, we also need to set Image Type to Sliced.
In order to scale and place the image, we select the last Transform Tool, which we can find in top-left corner of Unity, as shown in the next screenshot. It is called the Rect Tool, and it can easily be selected by pressing the hotkey T. While we need different tools to translate, rotate, and scale 3D objects, since they have many degrees of freedom, we can perform all of these operations with just one tool when we deal with a 2D object:
After we have selected the image from the scene view, four blue points appear on the corners. These are the control points of the Rect Tool.We can drag one of them to scale the image.If you want to keep the images' original proportions, you can hold down Shift while you are dragging the blue points.
Furthermore, if you hold down Alt instead of Shift, you can simultaneously scale the object in two directions symmetrically.
Finally, you can also resize the image by clicking on the edges instead of the corners and dragging them.
The new UI system of Unity allows us to add images to the UI in a very simple way. The Image (script) component takes a Source Image and draws it on the screen. However, this happens only if the object to which this component is attached is inside Canvas. In fact, Unity calls functions to draw the UI only if they are inside Canvas.
In the preceding examples, we used the Rect Tool to scale and place the image, because every UI element is represented as a rectangle for the purpose of this layout.
Rotating an image it's crucial in designing good UIs. Moreover, all the rotations depends by the pivot point. Thus, the aim of the following section is to give an overview of the concepts to start to experiment and learn how to use properly this tools.
We can also rotate the image by slightly moving the cursor away from the corners until it looks like a rotation symbol. Then, we can click and drag it in either direction to rotate the image. We can also change the pivot point. After selecting the image in the scene view, just click and drag the blue circle at the center of the image. By doing this, we can rotate images in different ways. You can better understand this concept by paying attention to the following image, which shows the same rectangle rotated with two different pivot points:
The four black squares are our referring points to understand the difference. Both the rectangles are rotated by the same angle. In the upper rectangle, the pivot point (blue circle) is in the middle, whereas in the lower rectangle, it is moved to the left side.
Furthermore, changing the pivot point could lead to an interesting variation in our UI when this is animated or controlled by scripts. For instance, we should definitely try to experiment with different locations of pivot points in the Creating an extendable element with a final fade effect and Creating an extendable and rotating element with a final fade effect recipes in Chapter 5, Decorating the UI.
Often in games, UI elements are not designed to be rectangular. Thus, a quick way to change their shape is through masking. One of the basic shapes is a circle. Therefore, in this recipe, you will learn how to make an image circular. This could be useful, for example, to surround a character icon circularly or to create special circular buttons. In order to achieve this, we will use the Mask component.
If you are using Photoshop, you can easy create this mask using the ellipse tool. While holding down the Shift key, click on the top-left corner and drag it to the bottom-right corner.
If you don't have a graphics program or you don't want to use a graphics program, you can use the image provided along with the code featured in this book.
As we have seen, Unity uses another image to create the mask. This is the reason the Mask (Script) component is attached to the object that has an Image (Script) component. As a result, it is possible to create any shape that we want for the mask. In fact, the only thing we need to keep in mind is that the white sections of the mask texture will be the parts that are visible.
Many fantasy games have huge worlds, along with very large maps, so in order to show them in the UI, they are usually scrollable. This allows the player to explore the map in sections without showing it entirely at once.
This recipe explains how to achieve this using the Mask (Script) component, which we have already used in the previous recipe, and the Scroll Rect (Script) component. The latter will handle the logic that will allow the UI elements to be scrollable.