29,99 €
A functional UI is an important component for player interaction in every type of video game. Along with imparting crucial statistical information to the player, the UI is also the window through which the player engages with the world established by the game. Unity's tools give you the opportunity to create complex and attractive UIs to make your game stand out.
This book helps you realize the full potential of Unity's powerful tools to create the best UI for your games by walking you through the creation of myriad user interface components.
Learn how to create visually engaging heads-up-displays, pause menus, health bars, circular progress bars, animated menus, and more. This book not only teaches how to lay out visual elements, but also how to program these features and implement them across multiple games of varying genres.
While working through the examples provided, you will learn how to develop a UI that scales to multiple screen resolutions, so your game can be released on multiple platforms with minimal changes.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 433
Veröffentlichungsjahr: 2018
Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Acquisition Editor:Noyonika DasContent Development Editor:Roshan KumarTechnical Editor:Sachin SunilkumarCopy Editor: Shaila KusanaleProject Coordinator:Devanshi DoshiProofreader: Safis EditingIndexer:Pratik ShirodkarGraphics:Jason MonteiroProduction Coordinator:Shraddha Falebhai
First published: April 2018
Production reference: 1250418
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78712-552-0
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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.
Dr. Ashley Godbold is a programmer, game designer, artist, mathematician, and teacher. She holds a Bachelor of Science in Mathematics, a Master of Science in Mathematics, a Bachelor of Science in Game Art and Design, and a Doctor of Computer Science in Emerging Media where her dissertation research focused on educational video game design. She also authored Mastering Unity 2D Game Development: Second Edition (Packt Publishing). She enjoys playing video games and watching anime with her husband, daughter, and two cats.
Adam Larson started programming professionally in 2005. He has shipped 14 console games, 2 PC titles, and 8 mobile games. In 2012, he founded a company that focused on using Unity for business applications. He spent the following 5 years building a million-dollar agency that built high-end software. Recently, he moved to another start-up, which is focusing on revolutionizing the banking industry. When he isn't doing something with technology, you will find him spending time with his wife and 3 kids.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Mastering UI Development with Unity
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Designing User Interfaces
UI and GUI
Four game interface types
Layout
Color schemes
Interface metaphors
Resolution and aspect ratio
Changing the aspect ratio and resolution of the game view
Building for a single resolution
Resetting the resolution
Method 1 – PlayerPrefs.DeleteAll()
Method 2 – Deleting PlayerPref files
Building for a single aspect ratio
Setting the orientation
Summary
Canvases, Panels, and Basic Layouts
UI Canvas
Rect Transform component
Canvas component
Screen Space-Overlay
Screen Space-Camera
World Space
Canvas Scalar component
Constant Pixel Size
Scale with Screen Size
Constant Physical Size
World
Graphic Raycaster component
Canvas Renderer component
UI Panel
Rect Transform
Rect Tool
Positioning modes
Rect Transform component
Rect Transform edit modes
Anchor and Pivot Point
Canvas Group component
Introducing UI Text and Image
Examples
Laying out a basic HUD
Placing a background image (2D game)
Setting up a basic pop-up menu
Summary
Automatic Layouts
Types of Automatic Layout Groups
Horizontal Layout Group
Padding
Spacing
Child Alignment
Control Child Size
Child Force Expand
Vertical Layout Group
Grid Layout Group
Cell Size
Start Corner and Start Axis
Constraint
Layout Element
Ignore Layout
The Width and Height properties
Min Width and Height
Preferred Width and Height
Flexible Width and Height
Fitters
Content Size Fitter
Aspect Ratio Fitter
Examples
Laying Out an HUD Selection Menu
Laying Out a Grid Inventory
Summary
The Event System and Programming for UI
Accessing UI elements in code
UnityEngine.UI namespace
UI variable types
The Event System
Event System Manager
First Selected
Send Navigation Events
Drag Threshold
Input Manager
Input functions for buttons and key presses
GetButton
GetAxis
GetKey
GetMouseButton()
Input Modules
Standalone Input Module
Hololens Input Module
Base Input Module/Pointer Input Module
Event Trigger
Event Types
Pointer events
Drag and Drop events
Selection events
Other events
Adding an action to the event
Event inputs
Raycasters
Graphic Raycaster
Other Raycasters
Examples
Showing and hiding pop-up menus with keypress
Using KeyCode with the Inventory Panel
Using Input Manager with the pause panel
Pausing the game
Dragging and dropping inventory items
Summary
Buttons
UI Button
Button component
Transitions
None
Color Tint
Sprite Swap
Animation
Navigation
Examples
Navigating through Buttons and using First Selected
Laying out the Buttons
Setting the explicit navigation and First Selected
Loading scenes with Button presses
Button Animation Transitions
Mute buttons with image swap
Summary
Text, Images, and TextMesh Pro-Text
UI Text
Text component
The Text and Character properties
Paragraph properties
The Color and Material properties
Raycast Target properties
Markup format
Font style
Font color
Font size
Importing new fonts
Font Size
Rendering Mode
Character
Ascent Calculation Mode
Dynamic font settings
Importing font styles
Custom fonts
UI Image
Image component
Image Type
Simple
Sliced
Tiled
Filled
UI effect components
Shadow
Outline
Position as UV1
TextMesh Pro-Text
Text Input Box
Font Settings
Extra Settings
Examples
Animated text
Creating a Background Canvas prefab and a new scene
Laying out the Text Box Windows
Animating the Text Box text
Custom font
Adjusting the character spacing and changing the font size
Horizontal and circular health/progress meters
Horizontal health bar
Circular progress meter
Wrapped text with Gradient
Summary
Masks and Other Inputs
Masks
Mask component
Rect Mask 2D component
UI Toggle
Toggle component
Toggle default event – On Value Changed (Boolean)
Toggle Group component
UI Slider
Slider component
Slider default event – On Value Changed (Single)
UI Scrollbar
The Scrollbar component
Scrollbar default event – On Value Changed (Single)
UI Scroll View
Scroll Rect component
Movement properties
Properties concerning scrolling speed
Properties of the Scrollbars
Scroll Rect default event – On Value Changed (Vector2)
UI Dropdown and TextMeshPro – Dropdown
Dropdown Template
The Dropdown component
Caption properties
Template properties
Option properties
Dropdown default event – On Value Changed (Int32)
UI Input Field
Input Field component
Properties of entered text and onscreen keyboards
Content Types
Line Types
Input Types
Keyboard Types
Character Validation options
Properties of the caret and selection
Input field default events – On Value Changed (String) and On End Edit (String)
TextMeshPro – Input Field
TMP_Input Field component
Input Field settings
Control settings
TextMeshPro - Input Field default events – On Select (String) and On Deselect (String)
Examples
Making a scroll view from a pre-existing menu
Creating a dropdown menu with images
Laying out the dropdown with caption and item images
Using the information from the dropdown selection
Summary
Animations and Particles in the UI
Animation clips
Animation Events
Animator Controller
The Animator of Transition Animations
Animator layers
Setting Animation Parameters in scripts
Animator behaviours
Particles in the UI
Examples
Animating pop up windows to fade in and out
Setting up the animations
Setting the Animator's Parameters with code
Animating a complex loot box with Particle System
Setting up the animations
Creating a Particle System that displays in the UI
Building a State Machine and timing the animations
Summary
World Space UI
When to use World Space
Appropriately scaling text in the Canvas
Other considerations when working in World Space
Examples
2D World Space status indicators
3D hovering health bars
Summary
Mobile-Specific UI
Recommended button sizes
Full screen/screen portion taps
The thumb zone
Multi-touch input
Accelerometer and gyroscope
Device resources
Examples
Adding press-and-hold/long-press functionality
Creating a static four-directional virtual D-pad
Creating a floating eight-directional virtual analog stick
Setting up the eight-directional virtual analog stick
Making the eight-directional virtual analog stick float
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
There are a multitude of built-in UI elements that can be incorporated into a game built in Unity. This book will help you master Unity's UI system by describing indepth the various UI objects, functionalities, and properties, and providing step-by-step examples of their implementation.
This book is intended for game developers who have worked with Unity and are looking to improve their knowledge of the UI system introduced in Unity 4.6. Individuals looking for in-depth explanations of specific UI elements and individuals looking for step-by-step directions explaining how to implement UI items that appear in multiple game genres will also find this book helpful.
Chapter 1,Designing User Interfaces, covers basic information related to designing user interfaces. Additionally, a detailed explanation of setting the aspect ratio and resolution of a Unity project is discussed.
Chapter 2,Canvases, Panels, and Basic Layouts, begins exploring the development of a user interface by appropriately laying out UI elements within a Canvas. Panels will be used and an introduction to Text and Images will be provided. The examples included in this chapter show how to lay out a basic HUD, create a permanent background image, and develop a basic pop-up menu.
Chapter 3,Automatic Layouts, discusses how to implement the various automatic layout components to streamline the UI building process. The examples included within this chapter utilize the automatic layout functionality to create a selection menu in the HUD and a gridded inventory.
Chapter 4,The Event System and Programming for UI, explains how to program interactions for graphical and hardware user interfaces. The examples covered in this chapter explain how to use the keyboard to make menus appear and disappear, how to pause the game, and how to create a drag and drop inventory system.
Chapter 5,Buttons, explores the various properties of buttons. The examples in this chapter walk through how to set up keyboard and controller navigation of buttons, how to load scenes when buttons are pressed, how to create animated button transitions, and how to make buttons swap their images.
Chapter 6,Text, Images, and TextMesh Pro-Text, discusses the properties of images and text more thoroughly and demonstrates how to affect their properties via code. The examples at the end of the chapter show how to create a dialog box with text that animates as if it was being typed in, how to create a custom font, how to make horizontal and circular progress meters/health bars, and how to create text that wraps with a gradient.
Chapter 7,Masks and Other Inputs, covers a myriad of UI inputs, as well as masks. Examples showing how to make a scrolling menu and a drop-down menu with images are covered at the end of the chapter.
Chapter 8,Animations and Particles in the UI, is all about animating the UI. The examples in this chapter show how to animate menus to fade in and out, and how to make a complex loot box animation with particles that appear in front of the UI elements.
Chapter 9,World Space UI, showcases how to create UI elements that exist within the game scene as opposed to on the "screen" in front of all in-game items. The examples cover how to create an interactive UI for a 2D scene and interactive, hover health bars for a 3D scene.
Chapter 10,Mobile-Specific UI, showcases interactions that are specific to mobile and touchscreen devices. The examples in this chapter show how to recognize when a portion of the screen is tapped on, how to zoom when the pinch action is performed, how to create press-and-hold or long-press interactions, and how to create static and floating on-screen control pads.
To complete the examples discussed in this text, you will need the following:
Unity version 5.6 or higher
A PC with Windows 7, 8, or 10 (64-bit) or a Mac with OS X 10.9 or higher
An internet connection to access the Unity Asset Store
Basic knowledge of Unity and C# programming is recommended
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Mastering-UI-Development-with-Unity. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here:https://www.packtpub.com/sites/default/files/downloads/MasteringUIDevelopmentwithUnity_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The following script, AddSprite.cs, is attached to the UI Image."
A block of code is set as follows:
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
// Use this for initialization void Start () {
theImage.sprite=theSprite;
theImage.preserveAspect=true;
}
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "You can add an Event System manager to a GameObject by selecting Add Component | Event | Event System on the object's Inspector."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
When working with UI, it is important to understand a few design basics. This chapter will cover the foundation of designing UI as well as a few key concepts to start you off in the right direction.
In this chapter, we will discuss the following topics:
Defining UI and GUI
Describing the four types of interfaces
Choosing a UI layout and color scheme
Defining interface metaphors
Discerning and setting resolution and aspect ratio
This book is not about the art of designing UI. It is a technical text that discusses implementation of UI functionality. However, I do want to discuss some basic design principles of UI design. I don't expect you to be an amazing UI artist after reading this chapter. I do hope that you get some basic understanding of layout and design principles from this chapter, though, so that maybe your artist friends won't make too much fun of you.
So what exactly do UI and GUI stand for, and what's the difference? UI stands for user interface, and GUI (pronounced "gooey") stands for graphical user interface. To interface means to interact with, so the user interface is the set of devices that let the player interact with the game. The mouse, keyboard, game controller, touch screen, and so on are all part of the user interface. Graphical user interface is the subset of the user interface that is represented by graphics. So, onscreen buttons, drop-down menus, and icons are all part of a game's GUI.
This book will focus primarily on GUI design, but it will discuss some non-graphical aspects of user interface controls, like accessing data from the mouse, screen tap, keyboard, or controller.
As GUI is a subset of UI, many people (myself included) tend to just refer to the GUI as UI. In fact, Unity also refers to all the GUI items they provide templates for as UI. "Back in the day", the days before Unity 4.6, to implement visual UI in Unity, you had to use the "legacy GUI controls". These controls used the OnGUI() method. I believe one of the reasons that Unity refers to their new graphical user interface controls as UI rather than GUI is to make a distinction between the old GUI and the new UI. This, and the fact that I feel silly saying "gooey", is also why I refer to the graphical user interface we can implement in Unity as "UI".
Anything Unity replaces with new functionality gets marked as "legacy". Legacy items are only left available within Unity for backward compatibility.
As a general rule, if you are trying to find any information about working in Unity's UI and find reference to OnGUI(), move along! This code has been deprecated for a reason, and Unity no longer supports it. In fact, Unity explicitly states that you should not use it for a new project. There are a few diehard OnGUI() fans out there who want to hold on to the past, but I couldn't tell you why. In my experience, I have not found anything to be "undoable" in the "new" (it's not that new anymore) UI. While some things you may want to do will not be explicitly provided by the "new" UI system, a little bit of your own code can go a long way.
When you say "game UI", most people think of the HUD (heads-up display) that appears in front of all the in-game items. However, there are actually four different types of game interfaces: non-diegetic, diegetic, meta, and spatial.
Fagerholt and Lorentzon first described these four different interface types in the 2009 Beyond the HUD: User Interfaces for Increased Player Immersion in FPS Games: Master of Science Thesis. Since then, the terminology has been widely used throughout the field of UI game design. You can find the original publication at http://publications.lib.chalmers.se/records/fulltext/111921.pdf.
The distinction between the four is determined by a cross of the following two dimensions:
Diegesis: Is part of the story?
Spatiality: Is in the game's environment?
The following diagram demonstrates the cross relationship between the two questions and how they define the four types of interfaces:
Non-diegetic is the category that a game's HUD will fall in. This information exists purely for the player to view, and the characters within the game are not aware of its presence. It exists on the fourth wall of the game view and appears to be on the screen in front of everything. The examples of this type of UI are endless, as nearly every game has some non-diegetic UI elements.
Alternatively, a diegetic interface is one that exists within the game world and the characters within the game are aware of its presence. Common examples of this include characters looking at inventory or maps. The most commonly referred-to example of diegetic UI is the inventory and health display within Deadspace. The inventory displays in a holographic display window that pops up in front of the playable character, and they interact with it as you select their weaponry. His health is also indicated by a meter on his back. The inventory of Alone in the Dark (2008) is displayed in a diegetic way as well. While there are some UI elements that only the player can see, the main character views inventory within their jacket pockets and interacts with the items. Uncharted Lost Legacy and Far Cry 2 both use maps that the characters physically hold in the scene and interact with. Fallout 3 and Fallout 4 use a diegetic interface to display the inventory and map on the character's Pip-boy, which is permanently attached to their arm. Games also use this type of display when characters are in a vehicle or suit, where various displays appear on the shield, window, or cockpit.
Meta interfaces are interfaces that the characters in the game are aware of, but they are not physically displayed within the scene. Common examples of this are speed displays for racing games. Forza 7 actually uses a combination of meta and diegetic displays for the speedometer. A meta speed indicator is persistently on the lower-right corner of the screen for the player to see. Since the character is constantly aware of how fast they are driving, they would be aware of this speed indicator, therefore making it a meta interface. There is also a diegetic speedometer in the car's dash that is displayed when playing in first-person view. Another common usage of this type of display is a cell phone that appears on the screen but is implied the playable character is interacting with in. Persona 5, Catherine, and Grand Theft Auto 5 all use this interface type for cell phone interactions.
The last type of interface, spatial, exists in the scene, but the characters within the game are not aware of it. Interfaces that exist in the scene but that the characters are not aware of are incredibly common. This is commonly used to let the player know where in the scene interactable items are, what the in-game character is doing, or information about characters and items in the scene. For example, in Legend of Zelda: Breath of the Wild, arrows appear over the heads of enemies, indicating who Link will attack. Link is not actually aware of these arrows; they are there for the player to know who he is focusing on. Xenoblade Chronicles 2 uses a spatial interface to indicate where the player can dig; a shovel icon appears over the diggable areas.
When laying out the UI for your game, I strongly recommend checking other games of the same genre and seeing how they implemented their UI. Play the game and see whether it feels good to you.
If you are unsure of how to lay out your game's UI, I recommend dividing the game's screen into a guttered grid, like the one shown in the following diagram, and placing items within the non-guttered areas:
You can use as many grids as you want, but laying out the items with reference to the grid will help ensure that the UI is arranged in a balanced way.
In most cases, the HUD items should remain in the outer edges of the grid. Any UI that displays in the center grids will restrict the player view. So, this area is good for pop-up windows that pause the gameplay.
The device your game will be played on is important when determining layout. If there are a lot of buttons the player will interact with, they are generally best suited for the bottom or side portions of the screen if playing on a mobile device. This is due to the way players hold their phones and top-center part of the screen is the most difficult area to reach with their thumb. Additionally, reaching for this area will cause them to block the majority of the game view with their hand.
You'll note that when you play computer games, they tend to have much smaller and more cluttered UI than mobile and console games. This is due to visibility and interaction. Clicking on small objects with a mouse is significantly easier than tapping them with a finger or selecting them by scrolling through them with the d-pad. Also, the screen resolution is much bigger, allowing for more space to be taken up by the UI as compared to the game.
Fitts' Law is a commonly referenced principle of UI design. The gist of Fitts' law is don't make interactable UI small and far apart to increase user experience. Make the most important interactible items the largest and ensure that they are near each other.
The color you choose for your UI will play an important role in not just its visual appeal, but in the player's interpretation of what the UI does. The colors of the UI should stand out compared to the background, but it should also not stand out so much that it causes eye strain. There is no specific color scheme you have to use for your game, but as a general rule, split complementary color schemes are the best for reducing eye strain while also producing enough contrast to make items distinguishable.
Whenever possible, you should also avoid color combinations that will be indistinguishable to those who are color blind; if it's not possible, use other indicators to make items distinct.
The following websites offer very good information on designing accessible UI for color blindness:
http://blog.usabilla.com/how-to-design-for-color-blindness/
https://www.smashingmagazine.com/2016/06/improving-color-accessibility-for-color-blind-users/
When you design your UI, you should use metaphors when possible rather than words. Metaphors are symbols whose meanings are universally recognized. For example, most people will recognize the meaning of these buttons to be play, pause, menu, settings, close/cancel, confirm, mute, and save:
There are three main reasons for using these metaphors:
They are quicker to recognize than text
They don't clutter the UI as much as their words counter parts
You don't have to translate them!
The third reason is the reason I use them the most. All the games I produce for the company I work for need to be translated into six different languages, so I avoid using words whenever possible.
Theresolutionof a game is the pixel dimension of the screen. For example, a game could run at 1024x768. This means that the game is 1024 pixels wide and 768 pixels tall. The aspect ratio of a game is the ratio between the width and height (expressed width:height). Thisaspect ratioof a game is determined by dividing the resolution width by resolution height and then simplifying the fraction. So, for example, if your game has a resolution of 1024x768, the aspect ratio would be as follows:
Here, the fraction 4/3 is the aspect ratio 4:3.
The following diagram provides a list of common aspect ratios and relatedresolutions:
When it comes to UI, the resolution of your game will be incredibly important. If you'll build to a single resolution/aspect ratio, the UI will be much easier to deal with. However, if you'll build a game that you want to run on multiple resolutions/aspect ratios (for example, a mobile project), you want your UI to scale appropriately, and you want to be able to easily change the resolution of your game so that you can test that it is scaling properly.
Even if you will allow your resolution and aspect ratio to vary, you should still decide on a default resolution. This default resolution represents the resolution of your ideal design. This will be the resolution that your initial design and UI layout is based on, so if the resolution or aspect ratio varies, the UI will try to maintain the same design best as it can.
You can easily switch between different resolutions and aspect ratios in theGametab. This will allow you to see how your UI scales at the different resolutions and aspect ratios:
If you navigate to your
Game
tab, you will see the words
Free Aspect
. Clicking on
Free Aspect
will reveal a menu that shows various aspect ratios and a single
1024x768
resolution
that is labeled
Standalone:
Free Aspectmeans that the window will scale to whatever resolution you set by changing the size of the game window. So by moving the frame around on the game window, you will change the aspect ratio. You can see this in effect easily by setting your Editor layout to one that shows both the Screen andGametabs open simultaneously. For example, setting the Layout to 2 by 3 will do this.
You can change the layout by selecting the word
Default
that appears in the upper-right hand corner of the Unity Editor.
Now the
Game
and
Scene
tabs will both be visible on the left-hand side of your screen. Zoom out of your scene tab very far so that the square representing the camera looks small, as shown:
Now, reduce the size of the game tab so that it is a very small thin rectangle. You will see that the main camera is now also displaying as a very small thin rectangle, because we are in
Free Aspect
ratio mode:
You can select another aspect ratio, like
5:4
, and you will see that as you rescale the game window, the blue area representing the actual game will maintain a
5:4
ratio and black bars to fill in any extra spacing. The camera will also maintain that ratio:
Standalone (1024x768)
will attempt to emulate the 1024x768 resolution. It's pretty likely that the window you have set for the
Game
tab is not big enough to support 1024x768 pixels; if so, it will be scaled as indicated in the following screenshot:
If the resolution or aspect ratio you want to use is not available in the resolution drop-down menu, you can add your own item to this menu by selecting the plus sign. If you want to create a set resolution item, setTypetoFixed Resolution. If you want to create a set aspect ratio item, setTypetoAspect Ratio:
For example, if I wanted to have a resolution item that represented the iPhone 6, add an item with the settings displayed in the following screenshot:
Once you hitOK, the iphone 6 item will be displayed at the bottom of the list. When you select it, the camera and visible area of theGametab will maintain the aspect ratio created by a1334x750resolution:
If you are creating a game that you plan to build on the PC, Mac, & Linux Standalone target platform, you can force the resolution to always be the same. To do so, go to Edit | Project Settings | Player. Your Inspector should now display the following:
You may have more or fewer platforms displayed here; it depends on the modules you have installed with Unity.
To force a specific resolution on a PC, Mac, & Linux Standalone game, deselectDefault is Native Resolution. Then, the options for inputtingDefault Screen WidthandDefault Screen Heightwill be made available to you, and you can enter the desired resolution values. You must also setDisplay Resolution DialogtoDisabled. Then, when you build your game, it will build play in a window of the size you specified.
The following screenshot shows the settings for forcing your game to display at 1024x768 in the Player Settings forPC, Mac, & Linux Standalone:
You can also force a specific resolution with aWebGLbuild. There are a few less options to worry about, but the general concept is the same. The following screenshot shows the settings for forcing your game to display at1024x768in the Player Settings forWebGL:
Annoyingly, if you build and run a PC, Mac, & Linux Standalone game with one set of resolution settings, and then try to rebuild with a different set of resolution settings, your new settings will not update and the game will still build with the previous resolution. This may seem like a bug, but it is not. The Unity application is saving the screen settings under the PlayerPref save data.
If you find that you are unable to manually set your resolution settings, there are two methods you can attempt:
Deleting the
PlayerPrefs
with
PlayerPrefs.DeleteAll();
Physically deleting the
PlayerPrefs
files from the computer
I will outline the two methods for you.
You can create a menu item within the Unity Editor that will delete all of your PlayerPrefs for you. This is helpful for this issue as well as helping you delete saved data in other scenarios.
The following method is modified from the one found athttp://answers.unity3d.com/questions/516517/why-doesnt-standalone-build-resolution-settings-af.html.
To create a menu item within the Unity Editor that will delete all of your PlayerPrefs, complete the following steps:
Create a new folder in your
Assets
folder called
Editor
.
Create a new C# Script and name it
DeletePrefs.cs
within the
Editor
folder. It will not work unless it is placed in a folder called
Editor
, so be sure to do that:
Open the
DeletePrefs.cs
script and give it the following code:
using UnityEditor;using UnityEngine;public class DeletePrefs : EditorWindow { [MenuItem("Edit/Delete All PlayerPrefs")] public static void DeletePlayerPrefs(){ PlayerPrefs.DeleteAll(); Debug.Log("delete prefs"); }}
Save the script.
A new option,
Delete All PlayerPrefs
, will now be at the very bottom of the
Edit
menu. Select
Delete All PlayerPrefs
. If performed correctly, you should see
delete prefs
in the
Console
log.
Rebuild the game and see whether the new resolution settings "stick".
I have found that Method 1 doesn't always work for me and sometimes my resolution settings are not reset. If you are unable to get Method 1 to work for you (or you just feel like doing it another way), you can find the PlayerPref files on your computer and delete them manually. To delete the files manually, complete the following steps:
Determine
Company Name
and
Product Name
from
PlayerS
ettings
by navigating to
Edit
|
Preferences
|
Player Settings
:
Now, select (Windows)
Start
and type
regedit
. Select the
regedit
program when it becomes available to you:
The Registry Editor should now be open. Navigate to the folders that represent the
Company Name
and
Product Name
you found in step 1, by the following path:
Computer
HKEY_CURRENT_USER
Software
The Company Name Found In Step 1 (
DefaultCompany
)
The Project Name Found In Step 1 (
Mastering Unity UI Project
):
Once you select the appropriate folder, you should see the following items on the right-hand side of the Registry Editor:
Screenmanager Is Fullscreen
Screenmanager Resolution Height
Screenmanager Resolution Width
Select all three of the listed items and delete them:
Rebuild the game, and the new resolution settings should now be displaying.
Forcing a specific aspect ratio is possible in PC, Mac, & Linux Standalone builds. To do so, enableDisplay Resolution Dialogand check the aspect ratio you wish to use in theSupported Aspect Ratiossetting.
The following screenshot shows a game being built with a 4:3 aspect ratio:
When you build and run your game with the preceding settings, a dialog option will open and the player will be allowed to choose from multiple resolutions that fit that setting. The following screenshot shows the resolution dialog window with multiple4:3resolutions available:
When building for mobile devices, you can't specify resolution and aspect ratio. However, you can choose between screen orientations in mobile devices. There are two different orientations:LandscapeandPortrait.
Games built so that they are wider than they are tall are said to have landscape resolution. Games build that are taller than they are wide are said to have portrait resolution. For example, a16:9aspect ratio would be a landscape resolution, and a9:16aspect ratio would be a portrait resolution, as illustrated:
So, while you can't choose the exact aspect ratio of a mobile game, you can choose the orientation, which forces the aspect ratio to be either wider or taller. You can set the orientation by navigating toEdit | Preferences | Player Settingsand selecting the mobile device. If you are building for both iOS and Android, you will not have to set these properties for both. As you can see from the following screenshot, the asterisk next to the property ofDefault Orientationstates that the settings are shared between multiple platforms:
You can set the Default Orientation to eitherAutoRotation, or one of the other rotations, as shown:
Unity defines the following orientations as the following rotations:
When you select a rotation other than Auto Rotation as the Default Orientation, the game will only play at that orientation on the device. If you select Auto Rotation, you will have the option to select between multiple orientations:
In most cases, it is best to choose only theLandscapeorientations or only thePortraitorientations, but not all four. Generally, allowing all four orientations will cause issues with the game's UI.
Players tend to prefer to be able to rotate their games (especially if they're like me and like to play games in bed while their phone is charging), so unless you have a good reason to stop rotation, it's best to enable both Portrait and Portrait Upside Down or Landscape Right and Landscape Left.
This chapter laid the framework necessary to begin working with UI.
In this chapter, we discussed the following topics:
Defining UI and GUI
Describing the four types of interfaces
Choosing a UI layout and color scheme
Defining interface metaphors
Discerning and setting resolution and aspect ratio
In the next chapter, we will jump into working with the Unity UI system.
Canvases are the core of all Unity UIs. Every single UI element must be included within a Canvas for it to be able to render within a scene. This chapter covers all that you need to create basic UI in Unity.
It's important to start focusing on setting up a UI that will scale at multiple resolutions and aspect ratios early on, as trying to do so later will cause a lot of headache and extra work. This chapter focuses on creating a UI that scales appropriately.
In this chapter, we will discuss the following topics:
Creating UI Canvases and setting their properties
Creating UI Panels and setting their properties
Using the Rect Tool and Rect Transform component
Properly setting anchor and pivot points
How to create and lay out a basic HUD
How to create a background image
How to set up a basic pop-up menu
Every UI element you create must be a child of a UI Canvas. To see a list of all UI elements you can create within Unity, select Create | UI from the Hierarchy window, as shown in the following screenshot:
Every one of the UI items highlighted in the preceding screenshot are renderable UI items and must be contained within a Canvas to render. If you try to add any of those UI elements to a scene that does not contain a Canvas, a canvas will automatically be added to the scene, and the item you attempted to create will be made a child of the newly added Canvas. To demonstrate this, try adding a new UI Text element to an empty scene. You can do so by selecting Create | UI | Text.
This will cause three new items to appear in the Hierarchy list: Canvas, Text, and Event System, where the Text is a child of the Canvas.
Now that you have a Canvas in your scene, any new UI elements you add to the scene will automatically be added to this Canvas.
If you try to take a renderable UI element out of a Canvas, it will not be drawn to the scene.
You can also create an empty Canvas by selecting Create | UI | Canvas. When you create a new Canvas in a scene, if an Event System GameObject does not already exist within the scene, one will automatically be created for you (as you saw in the preceding screenshot). We'll discuss the Event System further in Chapter 4, The Event System and Programming for UI, but, for now, all you really need to know is the Event System allows you to interact with the UI items.
You can have more than one canvas in your scene, each with their own children.
When you create a Canvas, it will appear as a large rectangle within your scene. It will be significantly larger than that rectangle representing the camera's view:
The Canvas is larger than the Camera, because the Canvas Component has a scaling mode on it. The scaling mode by default equates one pixel within the UI to one Unity unit, so it's a lot bigger. A nice consequence of this large size is that the large size makes it really easy to see your UI items as a somewhat separate entity and keeps it from cluttering up your camera view.
Every newly created Canvas automatically comes with four components: Rect Transform, Canvas, Canvas Scaler, and Graphic Raycaster, as shown in the following screenshot:
Let's explore each of these components.
Every UI GameObject has a Rect Transform component as its first component. This component is very similar to the Transform component on non-UI GameObject, in that it allows you to place the object within the scene.
You'll note that when you first place a Canvas in the scene, you can't adjust the values within the Rect Transform, and there is a message stating Some values driven by Canvas, as shown in the preceding screenshot.
This message means you cannot control the position of the Canvas, because of the properties selected in the Canvas component. Adjustment of Rect Transform is disabled for Canvases that are in Screen Space-Overlay Render Mode and Screen Space-Camera Render Mode (determined by the Canvas component). In these two modes, the values shown are determined by the resolution of the game display and automatically takes up the full screen. When the Canvas is in World Space Render Mode, you can adjust the values as you see fit.
We will look at the Rect Transform and the various render modes more thoroughly momentarily.
The Canvas component allows you to select the CanvasRender Mode. There are three render modes: Screen Space-Overlay, Screen Space-Camera, and World Space. The different render modes determine where in the scene the UI elements will be drawn.
One reason for creating multiple canvases is to create canvases with different render modes.
Screen Space-Overlay is the default rendering mode. When you think of UI, usually the first picture of UI that pops in your head is the type that would be rendered in Screen Space-Overlay. This rendering mode overlays all the UI elements within the Canvas in front of everything in the scene. So, UI items like heads-up-displays (HUDs) and pop-up windows that appear on the same plane and the screen, will be contained within a Screen Space-Overlay Canvas.
Remember that when a Canvas is using the Screen Space-Overlay render mode, you cannot adjust the Rect Transform component of the Canvas. This is because the canvas will automatically resize based on the size of the screen (not the camera):
When you have Screen Space-Overlay selected, the following properties become available:
Pixel Perfect
: This option can make the UI elements appear sharper and less blurry. This can cause performance issues, so only use it if absolutely necessary.
Sort Order
: This option applies only when you have multiple canvases with
Screen Space-Overlay
render modes. The higher the number, the
closer
to the items within the canvas will appear to the person viewing the scene. In other words, higher-numbered canvases will appear
on top
of lower-numbered canvases.
Target Display
:
If you are creating a PC, Mac, Linux Standalone game, you can have different cameras display on up to eight different monitors. You can also have different UI for each monitor and also where you will tell the Canvas which of the displays it will render on.
Screen Space-Camera performs similar to Screen Space-Overlay, but it renders all UI elements as if they are a specific distance away from the camera. As you can see from the following screenshot, if there is no renderer camera selected, this rendering mode works exactly the same as the Screen Space-Overlay mode (as indicated by the warning message):
You can add either the Main Camera or a second camera as the Render Camera in the Screen Space-Camera render mode. This is the camera to which the canvas will draw. Once you add a camera to the Render Camera slot, the warning message will disappear and new options will be made available to you, as shown in the following screenshot:
When you have Screen Space-Camera selected, the following properties become available:
Pixel Perfect
: This is the same option as with
Screen Space-Overlay
.
Render Camera
: As stated earlier, this is the camera to which the canvas will draw.
Plane Distance
: This property tells the canvas how far away from the camera it should display.
Sorting Layer
: This property allows you to choose which
Sprite Sorting Layer
to display the Canvas.
Order in Layer
: This property determines the order in the
Sprite Sorting Layer
(chosen earlier) the Canvas will display. This order works similar to the way
Sort Order
works, with higher numbers appearing on top of lower numbers.
This rendering mode is helpful if you want a Canvas to render at a different perspective than your main camera. It is also helpful for creating a static background that will consistently scale with the camera in a 2D game. Since you can use Sprite Sorting Layer