39,59 €
If you are a Unity developer looking to explore the newest features of Unity 2021 and recipes for advanced challenges, then this fourth edition of Unity Cookbook is here to help you.
With this cookbook, you’ll work through a wide variety of recipes that will help you use the essential features of the Unity game engine to their fullest potential. You familiarize yourself with shaders and Shader Graph before exploring animation features to enhance your skills in building games.
As you progress, you will gain insights into Unity's latest editor, which will help you in laying out scenes, tweaking existing apps, and building custom tools for augmented reality and virtual reality (AR/VR) experiences. The book will also guide you through many Unity C# gameplay scripting techniques, teaching you how to communicate with database-driven websites and process XML and JSON data files.
By the end of this Unity book, you will have gained a comprehensive understanding of Unity game development and built your development skills. The easy-to-follow recipes will earn a permanent place on your bookshelf for reference and help you build better games that stay true to your vision.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 843
Copyright © 2021 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 authors, 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.
Associate Group Product Manager: Pavan RamchandaniPublishing Product Manager: Pavan RamchandaniSenior Editor: Sofi RogersContent Development Editor: Rakhi PatelTechnical Editor: Simran UdasiCopy Editor: Safis EditingProject Coordinator: Manthan PatelProofreader: Safis EditingIndexer: Tejal SoniProduction Designer: Shankar Kalbhor
First published: June 2013Second edition: October 2015Third edition: August 2018 Fourth edition: September 2021
Production reference: 1030921
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83921-761-6
www.packt.com
I dedicate this book to my daughter, Charlotte.
I dedicate this book to Martina, Tomás, and Sénan.
Foreword
Not so long ago, developing professional quality games meant licensing an expensive game engine or writing your own from scratch. Then, you needed to hire a small army of developers to use it. Today, game engines like Unity have democratized game development to the point where you can simply download the tools and start making the game of your dreams right away.
Well... kinda. Having a powerful game creation tool is not the same thing as having the technical knowledge and skills to use it effectively.
I started coding games as a kid on my trusty ZX Spectrum, Commodore 64 & later the Amiga. I've been working as a professional game developer since 2003. When I first took the plunge into learning Unity development to create the Fungus storytelling tool, I found a huge amount of online documentation, tutorials, and forum answers available for Unity developers. This makes getting started with Unity development relatively easy, but the information can also be quite fragmented. Often, the last piece of the puzzle you need is buried 40 minutes into an hour-long tutorial video or on the 15th page of a forum thread. The hours you spend looking for these nuggets of wisdom is time that would be better spent working on your game.
The beauty of the Unity Cookbooks is that Matt, Chico, and Shaun have distilled this knowledge into a neat collection of easy-to-follow recipes, and they have provided the scripts and complete working projects so that you can put it to use straight away.
In this latest edition for Unity 2021, Matt and Shaun have updated the recipes from the previous book and added new recipes to introduce many of the latest Unity features. These include topics such as Augmented Reality and XR web publishing, particle systems, 2D physics, the 2021 Unity Starter Assets packages, code coverage, and running Python scripts in Unity.
Getting started with Unity development is free and easy. When you're ready to take your skills to the next level, this book is an effective way to do just that. It covers a great deal in its hundreds of pages, and if you can master even half of what's here, you'll be well on the way to becoming a great Unity developer!
Chris GreganChief Architect, Romero Games: www.romerogames.ieAuthor of Fungus: fungusgames.com
Contributors
Matt Smith is a computing academic at TU Dublin, the Technological University of Dublin, Ireland, where he leads the DRIVE Research Group (Digital Realities, Interaction, and Virtual Environments). He has been researching and teaching interactive game and web technologies since he moved to Ireland in 2002. Matt started computer programming on a brand new ZX80 and submitted two games for his computing O-level exam in 1985. After nearly 10 years as a full-time student on a succession of scholarships, he gained several degrees in computing, including a Ph.D. in computational musicology. Since 1994, he has been a full-time computer science lecturer at the University of Winchester (UK), then Middlesex University (UK), and now TU Dublin (Ireland).
In 1985, Matt wrote the lyrics and was in the band whose music appeared on the B-side of the audio cassette carrying the computer game Confuzion (look up the game's Wikipedia page!). Matt is one of the documentation authors for the free, open source Fungus Unity visual scripting and dialogue system. He enjoys sports, martial arts, and music, playing several instruments enthusiastically, if not very well. To get away from the computer completely, he has taken up carpentry and is currently planning to build an oak staircase (with a landing!), which will be his biggest project yet...
Thanks to my family for all their support. Thanks also to the editors, reviewers, and readers who provided feedback and suggestions. Thanks to my students, who continue to challenge and surprise me with their enthusiasm for multimedia and game development. Special thanks to Kris for help with the VR recipes and Nina for the AR recipes. Also thanks to Justin in Limerick for keeping me sane with snooker, golf breaks, and the newly installed full-size table tennis table – and congratulations on getting that first-class degree summa cum laude in 2021! Many thanks to Shaun for coming on board to coauthor this edition; given all the additional challenges this year, I don't think this book would have been completed without him, and I look forward to future collaborations.
Shaun Ferns is an academic at TU Dublin, the Technological University of Dublin, Ireland, where he is a researcher in the DRIVE Research Group (Digital Realities, Interaction, and Virtual Environments) and an associate researcher at the Educational Informatics Lab (EILab) at OntarioTechU. Since 2016, he has been primarily researching and teaching multimedia development, and prior to that was involved in the delivery of several engineering programs. He is currently exploring the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts and serious games for the built environment.
Shaun began to "play" with Unity when designing and building his house in 2010, developing an architectural walk-through to support the development of the design of the new home. Since then, he has been working on several Unity-based cultural projects and hopes to complete one soon!
Since 2011, Shaun has taken up the challenge of playing the Irish tenor banjo and currently enjoys playing in Irish traditional music sessions with his friends. When not practicing, he can be found wandering the cliffs and mountains around Donegal or swimming its Atlantic shores.
Thanks to the students I have been fortunate to work with over the last 20 years; the energy, excitement, and courage in their work have been truly inspirational and continue to have an influence. Thanks also to the editors, reviewers, and readers who provided feedback and suggestions. I began to enjoy our conversations through your comments! Special thanks to Matt, a source of guidance and support throughout this process, and for sharing his love of multimedia development.
Alessandro Salvati is a bulky, bearded geekbear born in Sardinia, Italy and living in Liverpool. A nerd from the 80s, he is a passionate freelance self-taught Unity game developer and a proud gameplay programmer at Skyhook Games Ltd. He was the lead dev of several top-rated and featured games on mobile stores. His most renowned works are gamification experiences preserving cultural heritage – commissioned by the most prestigious Italian museums. He programmed and led “Father and Son” for The MANN in Naples, thricely praised by the Italian Prime Minister himself on public media, and the first game funded by an international archaeological museum. Alessandro raised awareness about anxiety/panic attacks with his little game “Anxiety Attacks.”
I want to thank:
My mother, Elisa, who’s on my side while Covid forcefully keeps dividing us, in two different countries for over a year.
All the friends in Oristano that I miss so much.
My dearest Antonio from Pomezia.
Kinjal Bari (Project Coordinator) and Manthan Patel (Associate Project Manager) from Packt Publishing, for being so patient and understanding during these months of worldwide craziness.
The UK government in the hope it lets me continue to live in the UK.
Sungkuk Park is a Berlin-based game developer. He majored in art studies at Hongik University in Seoul, Korea but turned into a software engineer in the gaming industry. He is interested in almost everything about gaming. He is now turning into a technical artist! These are his publications:
Author of
Seamless Society
, 21 July 2020, in collaboration with an online exhibition platform, DDDD
Author of
Wallpeckers: Breaking down the barriers between media
, an article in the Korean art magazine Misulsegye, March 2019
Author of
The Possibility of the Impossibility of the "Art Games"
, an article in the Korean Art magazine Misulsegye, February 2017
Translator and Editor of
Game Level Generation Using Neural Networks
, a featured post of Gamasutra
Title Page
Copyright and Credits
Unity 2021 Cookbook Fourth Edition
Dedication
Foreword
Contributors
About the authors
About the reviewers
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
Displaying Data with Core UI Elements
Technical requirements
Displaying a "Hello World" UI text message
Getting ready
How to do it...
How it works...
There's more...
Styling substrings with rich text
Displaying a digital clock
Getting ready
How to do it...
How it works...
Displaying a digital countdown timer
Getting ready
How to do it...
How it works...
Creating a message that fades away
Getting ready
How to do it...
How it works...
Displaying a perspective 3D Text Mesh
Getting ready
How to do it...
How it works...
There's more...
Making the text crawl as it does in the movie
Where to learn more
Creating sophisticated text with TextMeshPro
Getting ready
How to do it...
How it works...
There's more...
Rich text substrings for colors, effects, and sprites
Displaying an image
Getting ready
How to do it...
How it works...
There's more...
Working with 2D sprites and UI Image components
See also
Creating UIs with the Fungus open source dialog system
How to do it...
How it works...
Creating a Fungus character dialog with images
How to do it...
How it works...
There's more...
Further reading
Responding to User Events for Interactive UIs
Technical requirements
Creating UI Buttons to move between scenes
How to do it...
How it works...
There's more...
Animating button properties on mouseover
How to do it...
How it works...
Organizing image panels and changing panel depths via buttons
Getting ready
How to do it...
How it works...
There's more...
Moving up or down by just one position, using scripted methods
Displaying the value of an interactive UI Slider
How to do it...
How it works...
Displaying a countdown timer graphically with a UI Slider
Getting ready
How to do it...
How it works...
Setting custom mouse cursors for 2D and 3D GameObjects
Getting ready
How to do it...
How it works...
Setting custom mouse cursors for UI controls
Getting ready
How to do it...
How it works...
Interactive text entry with Input Field
How to do it...
How it works...
There's more...
Toggles and radio buttons via toggle groups
Getting ready
How to do it...
How it works...
There's more...
Creating text and image icon UI Drop-down menus
Getting ready
How to do it...
How it works...
There's more...
Adding images to a Dropdown control
Displaying a radar to indicate the relative locations of objects
Getting ready
How to do it...
How it works...
The Start() method
The Update() method
The FindAndDisplayBlipsForTag(...) method
The CalculateBlipPositionAndDrawBlip (...) method
The NormalizedPosition(...) method
The CalculateBlipPosition(...) method
The DrawBlip() method
There's more...
Inventory and Advanced UIs
Technical requirements
Creating a simple 2D mini-game – SpaceGirl
Getting ready
How to do it...
How it works...
Displaying single object pickups with carrying and not-carrying text
Getting ready
How to do it...
How it works...
The PlayerInventory script class
The PlayerInventoryDisplay script class
There's more...
Collecting multiple items and display the total number carried
Alternative – combining all the responsibilities into a single script
Displaying single-object pickups with carrying and not-carrying icons
Getting ready
How to do it...
How it works...
Displaying multiple pickups of the same object with multiple status icons
Getting ready
How to do it...
How it works...
There's more...
Revealing icons for multiple object pickups by changing the size of a tiled image
Using panels to visually outline the inventory UI area and individual items
Getting ready
How to do it...
How it works...
Creating a C# inventory slot UI to display scripted components
Getting ready
How to do it...
How it works...
There's more...
Modifying the game for a second inventory panel for keys
Using UI Grid Layout Groups to automatically populate a panel
Getting ready
How to do it...
How it works...
There's more...
Automatically inferring the number of inventory slots based on the number of GameObjects tagged Star
Adding a horizontal scroll bar to the inventory slot display
Automatically changing the grid cell size based on the number of slots in the inventory
Displaying multiple pickups of different objects as a list of text via a dynamic list of scripted PickUp objects
Getting ready
How to do it...
How it works...
There's more...
Ordering items in the inventory list alphabetically
Using a Dictionary and Enums to display text totals for different objects
Getting ready
How to do it...
How it works...
Creating a runtime UI Toolkit interface
Getting ready
How to do it...
How it works...
Further reading
Playing and Manipulating Sounds
Technical requirements
Playing different one-off sound effects with a single AudioSource component
Getting ready
How to do it...
How it works...
There's more...
Playing a sound at a static point in 3D world space
Playing and controlling different sounds each with its own AudioSource component
Getting ready
How to do it...
How it works...
Creating just-in-time AudioSource components at runtime through C# scripting
Getting ready
How to do it...
How it works...
There's more...
Adding the CreateAudioSource(...) method as an extension to the MonoBehavior class
Delaying before playing a sound
Getting ready
How to do it...
How it works...
Preventing an audio clip from restarting if it is already playing
Getting ready
How to do it...
How it works...
Waiting for the audio to finish playing before auto-destructing an object
Getting ready
How to do it...
How it works...
See also
Scheduling a sound to play at a certain time
Getting ready
How to do it...
How it works...
Audio visualization from sample spectral data
Getting ready
How to do it...
How it works...
There's more...
Adding visualizations to a second AudioSource component
Trying out different Fast Fourier Transform (FFT) window types
Synchronizing simultaneous and sequential music to create a simple 140 bpm music-loop manager
Getting ready
How to do it...
How it works...
There's more...
Adding visualizations to the four playing loops
Further reading
Creating 3D Objects, Terrains, Textures, and Materials
Technical requirements
Creating 3D primitives and adding materials and textures
Getting ready
How to do it...
How it works...
There's more...
Enhancing the scene – adding a spotlight and wood material
Creating a new Material asset file in the Project window and then setting its Albedo to a texture
Converting and importing 3D models into a project
Getting ready
How to do it...
How it works...
Highlighting GameObject materials on mouseover
Getting ready
How to do it...
How it works...
There's more...
Collider needed for custom meshes
Changing the material's color in response to mouse events
Fading the transparency of a material
How to do it...
How it works...
There's more...
Destroying objects when fading is complete
Using the GameObject's alpha as our starting alpha value
Using a coroutine for our fading loop
Creating geometry with ProBuilder
How to do it...
How it works...
Creating a house with ProBuilder
How to do it...
How it works...
Creating and texture-painting terrains
How to do it...
How it works...
Height painting terrains
Getting ready
How to do it...
How it works...
Adding Terrain holes
Getting ready
How to do it...
How it works...
There's more...
Further reading
2D Animation and Physics
Technical requirements
Flipping a sprite horizontally – the DIY approach
Getting ready
How to do it...
How it works...
There's more...
Flipping a sprite horizontally – using Animator State Chart and transitions
Getting ready
How to do it...
How it works...
There's more...
Instantaneous swapping
Animating body parts for character movement events
Getting ready
How to do it...
How it works...
Creating a three-frame animation clip to make a platform continually animate
Getting ready
How to do it...
How it works...
There's more...
Copying the animation relative to a new parent GameObject
Making a platform start falling once stepped on using a Trigger to move the animation from one state to another
Getting ready
How to do it...
How it works...
Creating animation clips from sprite sheet sequences
Getting ready
How to do it...
How it works...
Creating a platform game with tiles and tilemaps
Getting ready
How to do it...
How it works...
There's more...
Tile palettes for objects and walls
Using sprite placeholders to create a simple physics scene
Getting ready
How to do it...
How it works...
There's more...
Editing polygon Colliders for more realistic 2D physics
Getting ready
How to do it...
How it works...
Creating an explosionForce method for 2D physics objects
Getting ready
How to do it...
How it works...
There's more...
Clipping via Sprite Masking
Getting ready
How to do it...
How it works...
There's more...
Further reading
Characters, Game Kits, and Starter Assets
Technical requirements
Creating a game with the 3D Game Kit
How to do it...
How it works...
There's more...
Creating a game with the 2D Game Kit
Getting ready
How to do it...
How it works...
Importing third-party 3D models and animations from Mixamo
Getting ready
How to do it...
How it works...
There's more...
Looping the animation
Scripting events to control when animation clips are played
Swapping the Standard Assets Ethan for a different character
Getting ready
How to do it...
How it works...
Importing a 3D model and adding an Animation Controller
How to do it...
How it works...
Using scripts to control 3D animations
Getting ready
How to do it...
How it works...
There's more...
Importing and using a UMA free character
How to do it...
How it works...
There's more...
Getting started with the 2021 Starter Assets package
How to do it...
How it works...
Further reading
Web Server Communication and Online Version Control
Technical requirements
Setting up a leaderboard using PHP and a database
Getting ready
How to do it...
How it works...
There's more...
SQLite, PHP, and database servers
phpLiteAdmin
See also
Unity game communication with a web server leaderboard
Getting ready
How to do it...
How it works...
There's more...
Extracting the full leaderboard data for display within Unity
Using secret game codes to secure your leaderboard scripts
See also
Creating and cloning a GitHub repository
Getting ready
How to do it...
How it works...
There's more...
Learn more about DVCS
Learn more about Git at the command line
Using Bitbucket and Sourcetree visual applications
Learning about Mercurial rather than Git
Adding a Unity project to a local Git repository, and pushing files up to GitHub
Getting ready
How to do it...
How it works...
Unity project version control using GitHub for Unity
Getting ready
How to do it...
How it works...
There's more...
Further reading on GitHub for Unity
Pulling down updates from other developers
Unity Collaborate from Unity Technologies
Further reading
Controlling and Choosing Positions
Technical requirements
Using a rectangle to constrain 2D Player object movement
Getting ready
How to do it...
How it works...
There's more...
Drawing a gizmo yellow rectangle to visually show a bounding rectangle
Player control of a 3D GameObject (and limiting movement within a rectangle)
How to do it...
How it works...
There's more...
Drawing a gizmo yellow rectangle to visually show a bounding rectangle
Drawing thick gizmo lines
Choosing destinations – finding a random spawn point
Getting ready
How to do it...
How it works...
See also
Choosing destinations – finding the nearest spawn point
Getting ready
How to do it...
How it works...
There's more...
Avoiding errors due to an empty array
See also
Choosing destinations – respawning to the most recently passed checkpoint
Getting ready
How to do it...
How it works...
Moving objects by clicking on them
Getting ready
How to do it...
How it works...
Firing projectiles in the direction of movement
Getting ready
How to do it...
How it works...
Navigation Meshes and Agents
Technical requirements
NPC to travel to destination while avoiding obstacles
Getting ready
How to do it...
How it works...
NPC to seek or flee from a moving object
Getting ready
How to do it...
How it works...
There's more...
Using a Debug Ray to show a source-to-destination line
Constantly updating the NavMeshAgent's destination to flee from the player's current location
Maintaining a constant distance from the target ("lurking" mode!)
Point-and-click move to object
Getting ready
How to do it...
How it works...
There's more...
Creating a mouseover yellow highlight
Point-and-click move to tile
Getting ready
How to do it...
How it works...
There's more...
Using a yellow debug ray to show the destination of the AI agent
Point-and-click raycast with user-defined, higher-cost navigation areas
Getting ready
How to do it...
How it works...
There's more...
More intelligent pathfinding by setting different costs for custom-defined navigation areas such as mud and water
Improving the UX by updating a "gaze" cursor each frame
NPC NavMeshAgent to follow waypoints in a sequence
Getting ready
How to do it...
How it works...
There's more...
Working with arrays of waypoints
Increased flexibility with the WayPoint class
Controlling object group movement through flocking
Getting ready
How to do it...
How it works...
Creating a movable NavMesh Obstacle
Getting ready
How to do it...
How it works...
Further reading
Cameras and Rendering Pipelines
Technical requirements
Creating the basic scene for this chapter
Getting ready
How to do it...
How it works...
There's more...
Working with a fixed Main Camera
Getting ready
How to do it...
How it works...
Changing how much of the screen a camera renders to
Getting ready
How to do it...
How it works...
There's more...
Using Render Textures to send camera output to places other than the screen
Getting ready
How to do it...
How it works...
There's more...
Inverting our mirror camera horizontally
A simple snapshot of a scene at runtime
Working with Unity's multipurpose camera rig
How to do it...
How it works...
Using Cinemachine ClearShot to switch cameras to keep the player in shot
Getting ready
How to do it...
How it works...
There's more...
Unity Cinemachine tutorials
Will Goldstone's ClearShot tutorial
Adam Myhill's Cinemachine blog posts
Reading the installed Cinemachine documentation
Cinemachine and Timeline
Letting the player switch to a Cinemachine FreeLook camera
Getting ready
How to do it...
How it works...
Creating a project with the URP
Getting ready
How to do it...
How it works...
Adding a vignette effect
Getting ready
How to do it...
How it works...
There's more...
Creating an HDRP project with an HDRI skybox
Getting ready
How to do it...
How it works...
Further reading
Shader Graphs and Video Players
Technical requirements
Playing videos by manually adding a VideoPlayer component to a GameObject
Getting ready
How to do it...
How it works...
There's more...
Using scripting to control video playback on scene textures
Getting ready
How to do it...
How it works...
There's more...
Downloading an online video (rather than a clip)
Ensuring a movie is prepared before playing
Getting ready
How to do it...
How it works...
There's more...
Ensuring that the movie has been prepared before playing it with coroutines
Outputting video playback to a RenderTexture asset
Getting ready
How to do it...
How it works...
Using scripting to play a sequence of videos back to back
Getting ready
How to do it...
How it works...
Creating and using a simple Shader Graph
How to do it...
How it works...
Creating a glow effect with Shader Graph
Getting ready
How to do it...
How it works...
Toggling a Shader Graph color glow effect through C# code
Getting ready
How to do it...
How it works...
There's more...
Further reading
Shader Graph online resources
Video player online resources
Advanced Topics - Gizmos, Automated Testing, and More
Technical requirements
Using Gizmo to show the currently selected object in the Scene window
How to do it...
How it works...
See also
Creating an editor snap-to-grid drawn by a Gizmo
How to do it...
How it works...
There's more...
Saving and loading player data – using static properties
Getting ready
How to do it...
How it works...
There's more...
Hiding the score before the first attempt is completed
See also
Saving and loading player data – using PlayerPrefs
Getting ready
How to do it...
How it works...
See also
Loading game data from a text file map
Getting ready
How to do it...
How it works...
Saving data to a file while the game is running
How to do it...
How it works...
See also
Generating and running a default test script class
How to do it...
How it works...
There's more...
Creating a default test script from the Project window's Create menu
Edit mode minimum skeleton unit test script
A simple unit test
How to do it...
How it works...
There's more...
Shorter tests with values in the assertion
Expected value followed by the actual value
Parameterizing tests with a data provider
How to do it...
How it works...
Unit testing a simple health script class
How to do it...
How it works...
Health.cs
TestHealth.cs
Creating and executing a unit test in PlayMode
How to do it...
How it works...
PlayMode testing a door animation
Getting ready
How to do it...
How it works...
There's more...
PlayMode and unit testing a player health bar with events, logging, and exceptions
Getting ready
How to do it...
How it works...
PlayMode testing
Unit tests
See also
Reporting Code Coverage testing
Getting ready
How to do it...
How it works...
Running simple Python scripts inside Unity
How to do it...
How it works...
Further reading
Particle Systems and Other Visual Effects
Technical requirements
Exploring Unity's Particle Pack and reusing samples for your own games
How to do it...
How it works...
Creating a simple particle system from scratch
How to do it...
How it works...
Using Texture Sheets to simulate fire with a particle system
Getting ready
How to do it...
How it works...
Making particles collide with scene objects
How to do it...
How it works...
There's more...
Simulating an explosion
Getting ready
How to do it...
How it works...
Using Invoke to delay the execution of an explosion
Getting ready
How to do it...
How it works...
There's more...
Further reading
Virtual and Augmented Reality (VR/AR)
Technical requirements
Setting up Unity for VR
How to do it...
How it works...
Setting up an Oculus Quest/2 in Developer Mode
Getting ready
How to do it...
How it works...
Creating a VR project for the Oculus Quest/2
Getting ready
How to do it...
How it works...
There's more...
Build failure due to Android version
Build failure due to "namespace cannot be found" error
Sideloading APK files to an Android device (such as the Quest headset)
Creating a VR project using the Mock HMD device
Getting ready
How to do it...
How it works...
Working with the Mozilla demo WebXR project
Getting ready
How to do it...
How it works...
There's more...
Using GitHub Pages to publish your WebXR project for free
Learning more about the WebXR example project
Fixing pink (shader/material) problems
The community maintaining more up-to-date XR resources
Fixing obsolete code errors
Adding 360-degree videos to a VR project
Getting ready
How to do it...
How it works...
There's more...
Playing 360-degree videos on the surface of a 3D object
Exploring the Unity AR samples
Getting ready
How to do it...
How it works...
There's more...
Targeting iOS device builds
Allowing Android APK file downloads on your phone
Setting up Unity for AR
How to do it...
How it works...
There's more...
Build failure due to Android version
Build failure due to Vulkan API graphics settings
Creating a simple AR Foundation project
Getting ready
How to do it...
How it works...
Detecting and highlighting planes with AR Foundation
Getting ready
How to do it...
How it works...
Creating an AR furniture previewer by detecting horizontal planes
Getting ready
How to do it...
How it works...
Creating a floating 3D model over an image target
Getting ready
How to do it...
How it works...
Further reading
Displaying Data with Core UI Elements
A key element that contributes to the entertainment and enjoyment of most games is the quality of the visual experience, and an important part of this is the user interface (UI). UI elements involve ways for the user to interact with the game (such as buttons, cursors, and text boxes), as well as ways for the game to present up-to-date information to the user (such as the time remaining, current health, score, lives left, or location of enemies). This chapter is filled with UI recipes to give you a range of examples and ideas for creating game UIs.
Every game and interactive multimedia application is different, and so this chapter attempts to fulfill two key roles:
The first aim is to provide step-by-step instructions on how to create a range of
Unity 2021
basic UI elements and, where appropriate, associate them with game variables in code.
The
second
aim is to provide a rich illustration of how UI components can be used for a variety of purposes. This will help you get good ideas about how to make the Unity UI set of controls deliver the particular visual experience and interactions for the games that you are developing.
Basic UI components can provide static images and text to just make the screen look more interesting. By using scripts, we can change the content of these images and text objects so that the players' numeric scores can be updated, or we can show stickmen images to indicate how many lives the player has left. Other UI elements are interactive, allowing users to click on buttons, choose options, enter text, and so on. More sophisticated kinds of UI can involve collecting and calculating data about the game (such as percentage time remaining or enemy hit damage; or the positions and types of key GameObjects in the scene and their relationship to the location and orientation of the player), and then displaying these values in a natural, graphical way (such as with progress bars or radar screens).
Core GameObjects, components, and concepts relating to Unity UI development include the following:
Canvas
: Every UI element is a child (or sub-child)
of a
Canvas
. There can be multiple
Canvas
GameObjects in a single scene. If a
Canvas
is not already present, then one
will
automatically be created when a new UI GameObject is created, with that UI object as the child of the new
Canvas
GameObject.
EventSystem
: An
EventSystem
GameObject is
required to manage the interaction events for UI controls. One will automatically be created with the first UI element. Unity generally only allows one
EventSystem
in any scene (some proposed code for multiple event systems can be found at
https://bitbucket.org/Unity-Technologies/ui/pull-requests/18/support-for-multiple-concurrent-event/diff
).
Visual UI
controls
:
The visible UI
controls
include
B
utton
,
Image
,
Text
,
and
Toggle
.
The
Rect Transform
component
: UI GameObjects are special 2D GameObjects that take up a rectangle on a 2D plane.
Unity gives all UI GameObjects the special
Rect Transform
component,
which has
some
different properties to the scene's GameObject
Transform
component
(with its straightforward
X
/
Y
/
Z
position, rotation, and scale properties). Associated with
Rect Transforms
are pivot
points (reference points for scaling, resizing, and rotations) and anchor points.
The following diagram shows the four main categories of UI controls, each in a Canvas GameObject and interacting via an EventSystem GameObject. UI controls can have their own Canvas, or several UI controls can be in the same Canvas. The four categories are static (display-only) and interactive UI controls, non-visible components (such as ones to group a set of mutually exclusive radio buttons), and C# script classes to manage UI control behavior through logic written in the program code.
Both the Canvas and EventSystem GameObjects are automatically added to the Hierarchy window as soon as the first UI GameObject is added to a scene:
Rect Transforms for UI GameObjects represent a rectangular area rather than a single point, which is the case for scene GameObject transforms. Rect Transforms describe how a UI element should be positioned and sized relative to its parent. Rect Transforms have a width and height that can be changed without affecting the local scale of the component. When the scale is changed for the Rect Transform of a UI element, this will also scale font sizes and borders on sliced images, and so on. If all four anchors are at the same point, resizing Canvas will not stretch the Rect Transform. It will only affect its position. In this case, we'll see the Pos X and Pos Y properties, and the Width and Height properties of the rectangle in the Inspector window. However, if the anchors are not all at the same point, Canvas resizing will result in stretching the element's rectangle. So, instead of Width, we'll see the values for left and right – the position of the horizontal sides of the rectangle to the sides of Canvas, where Width will depend on the actual Canvas width (and the same for top/bottom/height).
Unity provides a set of preset values for pivots and anchors, making the most common values very quick and easy to assign to an element's Rect Transform. The following screenshot shows the 3 x 3 grid of the Anchor Presets window, which allows you to make quick choices about the left, right, top, bottom, middle, horizontal, and vertical values. Also, the extra column on the right offers horizontal stretch presets, while the extra row at the bottom offers vertical stretch presets. Pressing the Shift + Alt keys sets the pivot and anchors when a preset is clicked:
There are three Canvas render modes:
Screen Space: Overlay
: In this
mode, the UI elements are displayed without
any
reference to any camera (there is no need for any
Camera
in the scene). The UI elements are presented in front of (overlaying) any sort of camera display of the scene's contents.
Screen Space
:
Camera
: In this
mode,
Canvas
is treated as a flat plane in the frustum (viewing space) of a
Camera
scene – where this plane is
always
facing the camera. So, any scene objects in front of this plane will be rendered in front of the UI elements on
Canvas
. The
Canvas
GameObject is automatically resized if the screen size, resolution, or
camera settings are changed.
World Space
: In this mode,
Canvas
acts as a flat plane in the frustum (viewing space) of a
Camera
scene – but the plane is not made to
always
face
Camera
. How the
Canvas
GameObject appears is just as with any other objects in the scene, relative to where (if anywhere), in the camera's viewing frustum, the
Canvas
window is located and oriented.
In this chapter, we are going to use the Screen Space: Overlay mode. However, all these recipes can be used with the other two modes as well.
Be creative! This chapter aims to act as a launching pad of ideas, techniques, and reusable C# scripts for your own projects. Get to know the range of Unity UI elements, and try to work smart. Often, a UI component exists with most of the components that you may need for something in your game, but you may need to adapt it somehow. An example of this can be seen in the recipe that makes a UI Slider non-interactive, instead of using it to display a red-green progress bar for the status of a countdown timer. We will take a detailed look at this in Displaying countdown times graphically with a UI Slider section in Chapter 2, Responding to User Events for Interactive UIs.
Many of these recipes involve C# script classes that make use of the Unity scene-start event sequence of Awake() for all GameObjects, Start() for all GameObjects, and then Update() every frame to every GameObject. Therefore, you'll see many recipes in this chapter (and the whole book) where we cache references to GameObject components in the Awake() method, and then make use of these components in Start() and other methods once the scene is up and running.
In this chapter, we will cover the following recipes:
Displaying a "Hello World" UI text message
Displaying a digital clock
Displaying a digital countdown timer
Creating a message that fades away
Displaying a perspective 3D Text Mesh
Creating sophisticated text with TextMeshPro
Displaying an image
Creating UIs with the Fungus open source dialog system
Creating a Fungus character dialog with images
For this chapter, you will need Unity 2021.1 or later, plus one of the following:
Microsoft Windows 10 (64-bit)/GPU: DX10, DX11, and DX12-capable
macOS Sierra 10.12.6+/GPU Metal-capable Intel or AMD
Linux Ubuntu 16.04, Ubuntu 18.04, and CentOS 7/GPU: OpenGL 3.2+ or Vulkan-capable, Nvidia or AMD
For each chapter, there is a folder that contains the asset files you will need in this book's GitHub repository at https://github.com/PacktPublishing/Unity-2021-Cookbook-Fourth-Edition.
The first traditional problem to be solved with new computing technology is to display the Hello World message, as shown in the following screenshot:
In this recipe, you'll learn how to create a simple UI text object with this message, in large white text with a selected font, in the center of the screen.
For this recipe, we have prepared the font that you need in a folder named Fonts in the 01_01 folder.
To display a Hello World text message, follow these steps:
Create a new
Unity 2D project
.
Import the provided
Fonts
folder, as described in the
Getting ready
section. Copy these font files into your Unity project – they need to be in your
Assets
folder.
In the
Hierarchy
window, add a
Text
GameObject to the scene by going to
GameObject | UI | Text
. Name this GameObject
Text-hello
.
Ensure that your new
Text-hello
GameObject is
selected in the
Hierarchy
window. Now, in
the
Inspector
window
, ensure the following properties are set:
Text
set to read
Hello World
Font
set to
Xolonium-Bold
Font Size
as per your requirements (large
–
this depends on your screen; try
50
or
100
)
Alignment
set to horizontal and vertical-center
Horizontal
and
Vertical Overflow
set to
Overflow
Color
set to white
The following screenshot shows the Inspector window with these settings:
In the
Inspector
window, click
Rect T
ransform
to make a dropdown appear, and click on the
Anchor Presets
square icon, which should result in several rows and columns of preset position squares appearing. Hold down
Shift
+
Alt
and click on the center one (
middle
row and
center column
):
Your
Hello World
te
xt
will
now appear, centered nicely in the
Game
window.
In this recipe, you added a new Text-hello GameObject to the scene. A parent Canvas and UI EventSystem will have also been automatically created. Also, note that by default, a new UI GameObject is added to the UI Layer – we can see this illustrated at the top right of the Inspector window in Figure 1.4. This is useful since, for example, it is easy to hide/reveal all UI elements by hiding/revealing this layer in the Culling Mask property of the Camera component of the Main Camera GameObject.
You set the text content and presentation properties and used the Rect Transform anchor presets to ensure that whatever way the screen is resized, the text will stay horizontally and vertically centered.