Unity UI Cookbook - Francesco Sapio - E-Book

Unity UI Cookbook E-Book

Francesco Sapio

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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:

EPUB
MOBI

Seitenzahl: 404

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Unity UI Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. UI Essentials
Introduction
Getting ready
Setting up a 2D texture to be a bordered sprite
How to do it...
How it works...
There's more...
Slicing with less than nine sections
See also
Resizing the UI according to the screen size and resolution
How to do it...
How it works...
See also
Adding and placing an image in the UI
How to do it...
How it works...
There's more...
Rotating the image and changing the pivot point
Adding a circular mask to an image
How to do it...
How it works...
See also
Making an image scrollable
How to do it...
How it works...
See also
Making text scrollable with a vertical slider
How to do it...
How it works...
There's more...
Scrolling multiple columns at once
Scrolling horizontally
Selecting buttons through the keyboard
How to do it...
How it works...
See also
Using UI layout components
How to do it...
How it works...
See also
2. Implementing Counters and Health Bars
Introduction
Implementing a score counter
How to do it...
How it works...
There's more...
Adding a remove points function
Using boldface in the rich text
Getting the score
See also
Implementing a lives counter
How to do it...
How it works...
There's more...
Changing the number of maxLives
Getting the number of lives
See also
Creating a modular coin counter
How to do it...
How it works...
There's more...
Removing coins
Adding score if the number of lives has reached the maximum
Getting the number of coins
See also
Creating a symbolic lives counter
How to do it...
How it works...
See also
Implementing a linear health bar
How to do it...
How it works...
There's more...
See also
Implementing a radial health bar
How to do it...
How it works...
There's more...
Having a health bar that isn't necessarily 360°
See also
Creating a health bar with armor
How to do it...
How it works...
See also
Using multiple bars to make a multibar
How to do it...
How it works...
See also
Developing a kingdom hearts health bar style
How to do it...
How it works...
See also
3. Implementing Timers
Introduction
Implementing a numeric timer
How to do it...
How it works...
There's more...
Getting the time variable
See also
Creating a linear timer
How to do it...
How it works...
There's more...
Running code when the timer expires
Creating a double-sided timer
See also
Implementing a radial timer
How to do it...
How it works...
See also
Creating a mixed timer
How to do it...
How it works...
There's more...
Changing the number of decimal points shown
Using a linear timer instead of a radial timer
See also
Creating a well-formatted timer
How to do it...
How it works...…
There's more...
Getting the time variable
See also
Developing a well-formatted countdown that changes
How to do it...
How it works...
There's more...
Getting the time variable
Running code when the time expires
Increasing tension by adding decimal points when the time is close to expiring
See also
4. Creating Panels for Menus
Introduction
Creating a toggle group
How to do it...
How it works...
There's more...
Giving the player the privilege not to choose one of the options
See also
Showing the slider value as a percentage
How to do it...
How it works...
Adding upper and lower bounds to the slider
How to do it...
How it works...
There's more...
Changing the color when a bound is reached
Expressing bounds as a percentage
Limiting the value that we can set in the Inspector
See also
Making UI elements affected by different lights
How to do it...
How it works...
See also
Making a draggable panel
How to do it...
How it works...
There's more...
Creating a draggable area for the panel
See also
Making a resizable panel
How to do it...
How it works...
See also
Creating a drag-and-drop element
How to do it...
How it works...
There's more...
Checking for dropped objects
Developing an MP3 player
How to do it...
How it works...
There's more...
Showing the name of the song
5. Decorating the UI
Introduction
Creating an extendable element with a final fade effect
How to do it...
How it works...
There's more...
Changing the speed for each axis
Fade-in instead of Fade-out
See also
Creating an extendable and rotating element with a final fade effect
How to do it...
How it works...
There's more...
Creating a shining effect
Creating a better shining effect
Using more than one axis to create 3D effects
Having control over each axis
Creating a butterfly
See also
Creating bars that go up and down
How to do it...
How it works...
There's more...
Adding a phase to use more than one bar
Adding bounds to our bar
Adding bounds and a phase
See also
Making a floating UI element
How to do it...
How it works...
There's more...
Creating a shaking effect
Creating a sparkle effect
Creating a better butterfly
See also
Adding shadows to text
How to do it...
How it works...
There's more...
Creating 3D letters
See also
Adding outlines to text
How to do it...
How it works...
There's more...
Creating a nice, soft outline
Creating better 3D letters
See also
6. Animating the UI
Introduction
Appearing and disappearing menu
How to do it...
How it works...
There's more...
Freezing time
Creating a menu with an entrance transition
How to do it...
How it works...
There's more...
Freezing time
Creating a menu with an idle animation
How to do it...
How it works...
Animating a button when the cursor is over it
How to do it...
How it works...
There's more...
Stretches back the button to the same speed of the Highlighted animation
Creating a pop-up menu
How to do it...
How it works...
Animating hearts of the symbolic lives counter
How to do it...
How it works...
Changing animation of the hearts of the symbolic lives counter through the script
Getting ready...
How to do it...
How it works...
There's more...
Adding a speed controller to customize speed in the Inspector and at runtime
Customizing each animation
7. Applying Runtime Customizations
Introduction
Making a button that changes color
How to do it...
How it works...
There's more...
Changing another image instead of the one attached to the button
See also
Creating a slider that changes colors gradually
How to do it...
How it works...
See also
Creating a slide shower using a discrete slider
How to do it...
How it works...
There's more...
Adding a text label to show the number of pictures
Making the slider continuous
Automating the slider setup
Adding pictures at runtime
See also
Creating a slider that changes a single color channel
How to do it...
How it works...
There's more...
Changing all other color channels
Changing the alpha channel
Integrating with lights instead of image components
See also
Making an input field with personal text validation at runtime
How to do it...
How it works...
There's more...
Checking the string when the player finished to type
Using for cycles for dynamic filtering
See also
Making an input field for a password with a lower bound limit for characters
How to do it...
How it works...
There's more...
Giving feedback to the player on why the string is not acceptable for the input field
See also
Changing the cursor at runtime
How to do it...
How it works...
There's more...
Animating the cursor
See also
8. Implementing Advance HUDs
Introduction
Creating a distance displayer
How to do it...
How it works...
There's more...
Testing the script
Optimizing the code by using a delayed update through coroutines
Multi target detecting
Beep sound
Increasing the ratio of the beep sound according to the distance
See also
Creating a directional radar
How to do it...
How it works...
There's more...
Testing the script
Changing the projection plane
Closest target detection
Adding a delay in the radar through a coroutine
More ideas on how to use the radar
Developing a subtitle shower
How to do it...
How it works...
There's more...
Testing the script
Adding a picture of the character who is talking
Adding the name of the character who is talking
9. Diving into 3D UIs
Introduction
Creating a 3D menu
How to do it...
How it works...
There's more...
Quick shadows
See also
Adding a smooth tilt effect
How to do it...
There's more...
Starting from the original rotation
Converting the speed in the smoothness factor
Inverting the axis
Asymmetric range for the rotation
Changing the reference of the mouse from the screen to an arbitrary rect
Creating and placing a 3D UI
How to do it...
There's more...
Using the 3D world
Making an animated 3D UI warning
How to do it...
How it works...
There's more...
Transforming the update function into a coroutine
Always orienting the warning towards the player
Adding a floating effect
See also
10. Creating Minimaps
Introduction
Getting ready
Creating a minimap
How to do it...
How it works...
There's more...
Setting an orthographic camera
See also
Implementing advanced features for minimaps
How to do it...
How it works...
There's more...
Limiting the boundaries of the minimap camera
Rotating the minimap according to where the player is facing
Smoothly rotating the minimap compass to point towards the relative north of the game environment
Improving the lighting within the minimap
Ideas for implementing the minimap in closed environments
Other techniques for minimaps
Index

Unity UI Cookbook

Unity UI Cookbook

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

Credits

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

About the Author

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.

About the Reviewers

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]>.

www.PacktPub.com

Support files, eBooks, discount offers, and more

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.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free Access for Packt account holders

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.

Preface

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.

What this book covers

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.

What you need for this book

The only software you need is Unity 5.x, which can be downloaded from the official website:

http://unity3d.com/

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.

Who this book is for

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.

Sections

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:

Getting ready

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.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

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: "Since we don't need to set the initial variables, we can erase the Start() function."

A block of code is set as follows:

public void Update() if (Input.GetKeyDown (key)) { EventSystem.current.SetSelectedGameObject( this.gameObject); }}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

using UnityEngine.UI; using UnityEngine.EventSystems; using UnityEngine; using System.Collections;

Any command-line input or output is written as follows:

C:\Program Files\Unity\Editor\Unity.exe

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."

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 <[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.

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 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.

Downloading the color images of this book

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.

Errata

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

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.

Questions

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.

Chapter 1. UI Essentials

In this chapter, we will cover the following recipes:

Setting up a 2D texture to be a bordered spriteResizing the UI according to screen size and resolutionAdding and placing an image in the UIAdding a circular mask to an imageMaking an image scrollableMaking text scrollable with a vertical sliderSelecting buttons through the keyboardUsing UI layout components

Introduction

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.

Getting ready

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.

Setting up a 2D texture to be a bordered sprite

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.

How to do it...

To begin, we need to import our image. We can do this by right-clicking on the Project panel and then selecting Import new asset....Using the navigation menu on your computer, locate an image and import it. As a result, the image will be in our project and it can be used everywhere within the current project.

Tip

Another way to add images to the project is by dragging and dropping them into the Project panel.

Next, we need to select our image in the Project panel. In fact, this allows us to display all the import settings in the Inspector window, which we can then tweak.In order to use images as part of the UI, Texture Type must to be set in Sprite (2D and UI). This can be changed through the Inspector window after we have selected them. However, if our project is set as a 2D project, the image in the project will have already been imported with Texture Type set correctly.Once we have done this, we click on the Sprite Editor button.In each side of the figure, we can find four green points. By dragging them, it is possible to divide the image into sections. By doing this, we create the borders of our image. Therefore, let's drag them a bit inside the picture so that we can see the borders. We have to pay attention when we have curved corners, which can be the case if we are working on a button. In fact, we need to ensure that all the green lines that belong to the border are beyond the curvatures of the corners. Otherwise, they will not be scaled as they should.Finally, we can click on the Apply button in the top-right corner of the Sprite Editor to save all our changes. After this, we can close the Sprite Editor, since we don't need it anymore.As a result, the image has borders, and therefore can be scaled as it should. How to properly place this inside our UI, since it requires us to set the Image (Script) component toSliced.

How it works...

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.

There's more...

The next subtopic will show us how to slice the sprite without using all of the nine sections.

Slicing with less than 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:

See also

Since having a bordered image is very important when the UI is scaled on different resolutions and platforms, maybe it could be worthwhile taking a deeper look at resolution scaling. The following recipe, Resizing the UI according to the screen size and resolution, will explain how to resize the UI according to the screen resolution.Moreover, it is possible to learn more about how to place an image in the UI in the Adding and placing an image in the UI recipe.

Resizing the UI according to the screen size and resolution

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.

How to do it...

If we check the previous recipe, we can see in the Hierarchy panel that Canvas is already present in our scene. This is because whenever we create a UI element and Canvas is not present in the scene, Unity will create it for us. Of course, we can also create it on our own, and this can be done by right-clicking on the Hierarchy panel and then navigating to UI | Canvas.Now that we have created Canvas, we can select it. In the Inspector, we can see all its properties and parameters, including all the components attached to it. By default, when a Canvas is created, the Canvas Scaler (Script) component is attached on it. Since this component can be removed, it may happen that it is not present anymore. In such cases, we can add it again by clicking inside the Inspector window on Add Component and then going to Layout | Canvas Scaler.Next, we have to change the Ui Scale Mode property to Scale With Screen Size and ensure that Screen Match Mode is set to Match Width Or Height. Furthermore, we can adjust the Match variable; for example, we can move the slider to the middle by changing the value to 0.5. We should now see this:As a result, every UI element inside Canvas will be scaled according to our project's screen resolution, and they will all adapt to the device on which the game is running.

How it works...

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.

See also

There are many other ways of scaling UI elements according to screen size to suit our requirements. To explore these methods, you can refer to the book Unity 3D UI Essentials by Simon Jackson, Packt Publishing, ISBN 139781783553617 (https://www.packtpub.com/game-development/unity-3d-gui-essentials).Furthermore, you can refer to the official documentation of Unity about this component athttp://docs.unity3d.com/Manual/script-CanvasScaler.html.

Adding and placing an image in the UI

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.

How to do it...

Let's start by importing the image into our project, as we did in the first recipe of this chapter. We can do this by right-clicking on the Project panel and selecting Import new asset. Of course, it is also possible to drag the asset into the same panel and skip the next step.We can navigate through our files to select the image that we want to import.If we select our image in the Project panel, it is possible to see all its properties in the Inspector.In order to use our image as Source Image of our UI, we need to change Texture Type to Sprite (2D and UI) in the Inspector. As you learned in the first recipe, if our project is set in 2D, all the images will have already been imported as sprites.Now, in the Inspector, there are different import settings. There is no need to change the settings for this recipe; it is important to understand these features so that we can properly import all our images into the project. These features include the format, along with the size and the compression method. If, for instance, we need to make the image file size smaller for performance. You can find references to them in the See also section of this recipe. Then, when we are satisfied with our choices, we can click on the Apply button so that the import settings are applied. This could take some minutes if you have changed the settings of many different images at once.Next, we need to create the UI image that will be in the UI. In order to add it to the scene, we have to right-click on the Hierarchy panel and then navigate to UI | Image. We should also ensure that it is inside the Canvas object.

Tip

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.

Inside the Image (Script) component, which we can find in the Inspector, we drag the image that we have imported inside the Source Image variable.

Tip

If our image is sliced, as we saw in the first recipe of this chapter, we also need to set Image Type to Sliced.

As a result, our image appears in the UI, but it has taken the dimensions and scaling of the Image object that we have created. Therefore, if we need to keep its original dimensions, we can click on Set Native Size in order to set them again.So that it is easier to work with the UI, set your scene view to 2D, as shown in the following screenshot, and zoom out and pan until you can clearly see your Canvas. At this stage, it is very large, so don't worry if you zoom out too much. Otherwise, you can use the hotkey F (or double-click on the image in the Hierarchy panel) to focus the camera on it:

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.

Tip

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.

In conclusion, we can place the image wherever we want to by clicking anywhere inside the rectangle and dragging. Again, keep in mind that all the UI elements, including the image, must be inside the Canvas in order to be drawn by Unity and displayed to the player.

How it works...

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.

There's more...

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.

Rotating the image and changing the pivot point

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:

Tip

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.

Adding a circular mask to an image

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.

How to do it...

First of all, we need to create a mask, which in this case should be circular. Since the mask is just another image, let's open a graphic program that we have. Then, we need to create a new image with the same pixels for the height and width so that the drawing canvas is a square.This step and the following step depend on the graphics program that you are using. Now, we have to draw a white circle in the middle of the image.Furthermore, we should also ensure that the background is transparent. From the following screenshot, you can get an idea of what the final outcome will look like (the program used for this is Photoshop):

Tip

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.

The next step is to import this mask into the project. To do this, right-click on the Project panel and select Import new asset.Unity will ask us to select the mask that we have just created. Therefore, locate the folder where you saved it and then import it.In order to see the settings of the imported mask as an image in the Inspector, we need to select it in the Project panel.Thus, if our project is not set in 2D, we should change the Texture Type in Sprite (2D and UI) in the Inspector and then click on Apply.Now, we need to create a new panel. We can do this by right-clicking on the Hierarchy panel and then going to UI | Panel. We should also ensure that we have it inside the Canvas object.Inside the Image (Script) component, we need to set our mask to the Source Image variable.In order to get the exact shape that we created in our graphics program, we need to bring the image back to its original proportions. This can be done by clicking on Set Native Size and then scaling uniformly (keeping Shift pressed) if needed.The next thing to do is transform our panel into a mask. So, we need to add the Mask (Script) component to our panel.Then, we need an image to put the mask on. Therefore, let's create an image inside the panel. To do this, we need to right-click on the Hierarchy panel and then go to UI | Image.Inside the Image (Script) component of the image, we need to select the picture that we want to mask. This can be done by dragging it into the Source Image variable of the component. As a result, it will be masked with a circle.If needed, we can click on Set Native Size and scale it uniformly.In this case, by using an ancient map, we can see what the final outcome should look like in the following picture:

How it works...

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.

See also

If you are looking for more information about the Mask component, you can refer to the Unity official documentation at http://docs.unity3d.com/Manual/script-Mask.html.

Making an image scrollable

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.

How to do it...

So that we don't have to start over again, we can use the mask that we created in the previous recipe. In fact, we can change what we have done there to achieve this scrollable effect.