35,99 €
Unleash your game development potential with Unity Cookbook, 5th Edition, designed to equip you with the skills and knowledge needed to excel in Unity game development. With over 160 expertly crafted recipes empowering you to pioneer VR and AR experiences, excel in mobile game development, and become a master of audio techniques.
In this latest edition, we've meticulously curated a collection of recipes that reflect the latest advancements in Unity 2023, ensuring you stay at the forefront of game development. You'll discover dedicated recipes for First/Third Person (Core) templates, create engaging mobile games, delve into Virtual and Augmented Reality, and go further with audio by exploring advanced techniques. Additionally, the book has been fully updated to incorporate the new input system and TextMeshPro, essential elements for modern game development.
From exploring C# scripting to crafting stylish UIs, creating stunning visual effects, and understanding shader development through Shader Graph, every chapter is designed to take you closer to your goal of becoming a proficient Unity developer.
So, whether you're aiming to develop the next hit game, enhance your portfolio, or simply have fun building games, this book will be your trusted companion on your journey to Unity proficiency.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 922
Unity Cookbook
Fifth Edition
Over 160 recipes to craft your own masterpiece in Unity 2023
Matt Smith
Shaun Ferns
Sinéad Murphy
BIRMINGHAM—MUMBAI
Unity Cookbook
Fifth Edition
Copyright © 2023 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.
Senior Publishing Product Manager: Larissa Pinto
Acquisition Editor – Peer Reviews: Gaurav Gavas and Jane D’Souza
Project Editor: Meenakshi Vijay
Content Development Editor: Davide Oliveri
Assitant Development Editor: Elliot Dallow
Copy Editor: Safis Editing
Technical Editor: Kushal Sharma
Proofreader: Safis Editing
Indexer: Subalakshmi Govindhan
Presentation Designer: Rajesh Shirsath
Developer Relations Marketing Executive: Sohini Ghosh
First published: June 2013
Second edition: October 2015
Third edition: August 2018
Fourth edition: September 2021
Fifth edition: November 2023
Production reference: 1281123
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 9781805123026
www.packt.com
We dedicate this book to Bobby O’Brien.
– Matt Smith & Sinéad Murphy
Dedicated to my amazing son, Sénan, a hero in the making.
– Shaun Ferns
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, and 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 Cookbook is that Matt, Chico, Shaun, and Sinéad 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, Matt, Shaun, and Sinéad have updated the recipes from the previous book and added new recipes to introduce many of the latest Unity features. There are some new chapters focusing on ProBuilder and mobile development; and other chapters include new topics such as non-horizonal AI NavMesh surfaces (think spiders crawling up walls and ceilings!), and advanced visual effects including vignettes and realistic animated water surfaces.
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 Gregan
Chief Architect, Romero Games: www.romerogames.ie
Author of Fungus: fungusgames.com
Matt Smith is senior lecturer at TU Dublin,the Technological University of Dublin, Ireland, specialising in XR and interactive multimedia. He leads the university’s DRIVE (Digital Realities, Interaction, and Virtual Environments) research group, and is currently supervising several PhD students in interaction design and XR technologies. In 1980, Matt started computer programming (on a ZX80). A few years later he submitted his first two games for the programming project component of his ‘O’-level computing certificate (aged 16). In 1985, Matt wrote the lyrics, and was a member of the band that played (and sang, sorry about that by the way) the music on the B-side of the audio cassette carrying the computer game Confuzion (the game/song has a Wikipedia page...). In 2024, No Starch Press will publish his PHP Crash Course. Matt is still (pleasantly!) surprised at the popularity of his Unity Cookbook series – whose beginning was a book proposal sent to Packt Publishing over 10 years ago.
I’m grateful to my coauthors, Shaun and Sinéad, without whom this book wouldn’t have been possible.
Many thanks to all my family. Thanks also to the editors, reviewers, and readers for their feedback. Thanks to my students, who continue to challenge and surprise me with their enthusiasm for multimedia and game development.
Shaun Ferns is an academic at TU Dublin, the Technological University of Dublin, Ireland, where he is a researcher in the DRIVE (Digital Realities, Interaction, and Virtual Environments) research group 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! 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.
First and foremost, I am grateful to the students I have had the privilege of teaching and learning alongside over the past two decades. Your energy, excitement, and courage have challenged me to think more deeply and creatively. I am deeply inspired by your commitment to making the world a better place.
I am also indebted to the editors, reviewers, and readers who have provided feedback on this book. Your insights and suggestions have helped me to refine my arguments and improve the clarity and accessibility of my writing.
I am especially grateful to Matt, who has been a steadfast supporter, both professionally and personally. Your guidance, encouragement, and shared love of Game design and development through Unity have made this journey even more rewarding. Delighted to also welcome Sinéad to the authorship team. I hope this is the start of a long-lasting collaboration!
I am also grateful to my family and friends, who have provided me with unwavering support throughout this process. Finally, I would like to thank the many people who have made contributions to my education and professional development over the years. I am grateful for your mentorship and guidance.
Sinéad Murphy is currently Data Analytics Manager for the Irish NGO Trócaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills, and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing, and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Many thanks to my coauthors, Matt and Shaun, it’s been a great experience working on my first book.
Thanks to my family for all their support. Thanks also to the editors and reviewers who provided feedback and suggestions.
Jerry Medeiros is a seasoned professional with over a decade of hands-on experience in immersive technology, focusing on games and extended reality. With a robust background in artificial intelligence, Jerry brings a unique perspective to the intersection of technology and interactive experiences. Holding a degree in game development with a specialization in interaction design, as well as a Master of Computer Science with research expertise in artificial intelligence, Jerry is well versed in cutting-edge technologies and their applications. Additionally, an MBA in Innovation further underscores Jerry’s commitment to driving creative and forward-thinking solutions in the tech industry.
To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:
https://packt.link/unitydev
Preface
Who this book is for
What this book covers
Technical requirements to get the most out of this book
Get in touch
Displaying Data with Core UI Elements
Creating a Font Asset file for use with TextMeshPro
Getting ready
How to do it...
How it works...
Displaying a “Hello World” UI text message
Getting ready
How to do it...
How it works...
There’s more...
Styling substrings with rich text
Exploring the TextMeshPro Examples and Extras
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...
There’s more...
Automatically add components with [RequireComponent(...)]
Creating a message that fades away
Getting ready
How to do it...
How it works...
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
Further reading
Learn more on Discord
Responding to User Events for Interactive UIs
Creating a UI Button to reveal an image
Getting ready
How to do it...
How it works...
There’s more...
Creating a UI Button to move between scenes
How to do it...
How it works...
There’s more...
Animating UI 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
Getting ready
How to do it...
How it works...
There’s more...
Detecting interactions with a single Toggle UI component
Getting ready
How to do it...
How it works...
Creating related radio buttons using UI Toggles
Getting ready
How to do it...
How it works...
Creating text UI Dropdown menus
How to do it...
How it works...
Creating image icon UI Dropdown menus
Getting ready
How to do it...
How it works...
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...
Further reading
Inventory and Advanced UIs
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 displaying 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
How it works...
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
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
Displaying multiple pickups of different objects as text totals via a dynamic Dictionary<> of PickUp objects and enum pickup types
Getting ready
How to do it...
How it works...
There’s more...
Separating responsibilities with MVC
Further reading
Learn more on Discord
Playing and Manipulating Sounds
Setting up the Third Person Character Controller project
How to do it...
How it works...
There’s more...
Fixing pink textures
Playing sound when a scene begins
Getting ready
How to do it...
How it works...
There’s more...
Create a GameObject with AudioSource linked to an AudioClip in a single step
Make the sound clip keep looping
Customizing other AudioSource settings
Removing redundant AudioListener components
Getting ready
How to do it...
How it works...
Enabling and customizing 3D sound effects
Getting ready
How to do it...
How it works...
There’s more...
Changing the way the volume changes with distance
Adding keys to customize the volume falloff curve
Adding effects with Audio Reverb Zones
Getting ready
How to do it...
How it works...
There’s more...
Customize Reverb settings with the User preset
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
A button to play a sound with no scripting
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
Creating 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
Recording sound clips with the free Audacity application
Getting ready
How to do it...
How it works...
Further reading
Textures, Materials, and 3D Objects
Creating a scene with 3D primitives and a texture
Getting ready
How to do it...
How it works...
There’s more...
Enhancing the scene – adding a spotlight
Creating material asset files and setting Albedo textures
Getting ready
How to do it...
How it works...
Exporting Blender files as FBX for use in Unity
Getting ready
How to do it...
How it works...
Importing FBX models into a Unity project
Getting ready
How to do it...
How it works...
There’s more...
Using Blender files directly in a Unity project
Highlighting GameObject materials on mouseover
Getting ready
How to do it...
How it works...
There’s more...
A collider needed for custom meshes
Changing the material’s color in response to mouse events
Fading the transparency of a material
Getting ready
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
Further reading
Learn more on Discord
Creating 3D Environments with Terrains
Creating and texture-painting terrains
Getting ready
How to do it...
How it works...
Unity terrain tools and samples for powerful height-painting
Getting ready
How to do it...
How it works...
There’s more…
Adding terrain holes
Getting ready
How to do it...
How it works...
Adding trees and vegetation
Getting ready
How to do it…
How it works...
Realistic water features for HDRP projects
How to do it...
How it works...
Further reading
Creating 3D Geometry with ProBuilder
Getting started with ProBuilder
Getting ready
How to do it...
How it works...
Transforming an object through scaling and coloring
Getting ready
How to do it...
How it works...
Creating a house with ProBuilder
Getting ready
How to do it...
How it works...
Exploring ProBuilder Boolean operations to add a window to our house
Getting ready
How to do it...
How it works...
Organizing level geometry as empty GameObject children
Getting ready
How to do it...
How it works...
Further reading
Learn more on Discord
2D Animation and Physics
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...
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
Animated Characters
Unity’s Third Person Character Controller assets
How to do it...
How it works...
Adding a Third Person Character Controller to a scene
Getting ready
How to do it...
How it works...
Adding a clothing accessory pickup for a character
Getting ready
How to do it...
How it works...
Swapping the Third Person Armature for a different character
Getting ready
How to do it...
How it works...
There’s more...
Extracting textures when colors are not showing
Creating a 3D character with Autodesk Character Generator
Getting ready
How to do it...
How it works...
There’s more...
Replace the robot character with your created character
Remove the Light child GameObject from the character Hierarchy
Selecting and downloading a character from Mixamo
Getting ready
How to do it...
How it works...
There’s more...
Using Mixamo to convert and fix character models
Selecting and downloading an animation clip from Mixamo
Getting ready
How to do it...
How it works...
Creating an animated NPC in Unity using a character and animation clip
Getting ready
How to do it...
How it works...
Using scripts to control 3D animations (old input system)
Getting ready
How to do it...
How it works...
Using scripts to control 3D animations (new input system)
Getting ready
How to do it...
How it works...
Further reading
Learn more on Discord
Saving and Loading Data
Saving data between scenes 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 data between scenes and games using PlayerPrefs
Getting ready
How to do it...
How it works...
See also
Reading data from a text file
Getting ready
How to do it...
How it works...
Loading game data from a text file map
How to do it...
How it works...
Writing data to a file
How to do it...
How it works...
There’s more...
Writing lists of objects to a JSON text file
Logging player actions and game events to a file
How to do it...
How it works...
There’s more...
Automatically log the username of the system user
See also
Reading data from the web
Getting ready
How to do it...
How it works...
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
Further reading
Controlling and Choosing Positions
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
An alternative approach to defining movement bounds
Player control of a 3D GameObject (and limiting movement within a rectangle)
Getting ready
How to do it...
How it works...
There’s more...
Drawing a thick gizmo yellow rectangle to visually show a bounding rectangle
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...
Further reading
Learn more on Discord
Navigation Meshes and Agents
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 in each frame
NPC NavMeshAgent to follow waypoints in sequence
Getting ready
How to do it...
How it works...
There’s more...
Working with arrays of waypoints
Increased flexibility with the WayPoint class
Creating a movable NavMesh Obstacle
Getting ready
How to do it...
How it works...
Joining several NavMeshes with a single NavMeshSurface
Getting ready
How to do it...
How it works...
Non-horizontal NavMeshes with multiple NavMeshSurfaces and NavMeshLinks
Getting ready
How to do it...
How it works...
Further reading
Cameras, Lighting, and Visual Effects
Creating the basic scene for this chapter
Getting ready
How to do it…
How it works...
There’s more...
Fixing pink textures
Working with a fixed Main Camera
Getting ready
How to do it...
How it works...
Changing how much of the screen a Camera renders
Getting ready
How to do it...
How it works...
Adding a top-down orthographic minimap Camera
Getting ready
How to do it...
How it works...
There’s more...
Adding a floating arrow to indicate the direction the player is facing in the minimap
Using a culling mask to avoid the sphere being rendered unintentionally
Creating an in-game mirror using a RenderTexture to send Camera output to a Plane
Getting ready
How to do it...
How it works...
There’s more...
Inverting our mirror Camera horizontally
Saving screenshots and RenderTextures to files
Getting ready
How to do it...
How it works...
There’s more...
Automate screenshot capture with OnTriggerEnter()
Capture screenshots as a Texture or RenderTexture
Using Cinemachine ClearShot to switch cameras to keep the player in shot
Getting ready
How to do it...
How it works...
A Camera to always look at and follow the Third Person Controller
Getting ready
How to do it...
How it works...
There’s more...
Adding the option to switch between a following camera and multiple ClearShot cameras
Adding film grain and vignette effects with URP postprocessing
Getting ready
How to do it...
How it works...
There’s more...
Adding a vignette effect
Creating an HDRP project with an HDRI skybox
Getting ready
How to do it…
How it works...
There’s more...
Using a skybox for default ground image
Creating and applying a cookie texture to a spotlight
Getting ready
How to do it...
How it works...
There’s more...
Adding more content and creating ground shadows
Using Cookies with Directional Lights
Baking light from an emissive material onto other scene GameObjects
Getting ready
How to do it...
How it works...
There’s more...
Emissive materials that do not contribute to lighting other objects in the scene
Further reading
Learn more on Discord
Shader Graphs and Video Players
Playing videos with the Video Player API
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...
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
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
Particle Systems and Other Visual Effects
Exploring Unity’s Particle Pack and reusing samples for your own games
How to do it...
How it works...
Creating a simple Particle Systems 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...
Destroying or damaging objects in a bomb blast radius
Adding camera shake when the bomb explodes
Using a Line Renderer to create a spinning laser trap
How to do it...
How it works...
There’s more...
Triggering an explosion when the player’s character collides with the beam
Further reading
Learn more on Discord
Mobile Games and Applications
Setting up your system for Android mobile app development
How to do it...
How it works...
Setting up your system for Apple iOS mobile app development
Getting ready
How to do it...
How it works...
Deploying the Third Person Character Controller Starter project for an Android device
Getting ready
How to do it...
How it works...
There’s more...
Changing the name of the app as it appears on a device
Copying APK files from a Windows PC to an Android device
Sideloading APK files from a Mac to an Android device
Downloading Android APK files on your phone
Deploying the Third Person Character Controller Starter project for an Apple device
Getting ready
How to do it...
How it works...
There’s more...
The device will not prepare for development
Creating and deploying a mobile game with Unity’s Runner Game project template
How to do it...
How it works...
Further reading
Augmented Reality (AR)
Exploring the Unity AR samples
How to do it...
How it works...
Creating an AR project with the AR (Core) template
How to do it...
How it works...
There’s more...
Deprecation warnings with the AR (Core) template
Build failure due to Vulkan graphics API settings
Build failure due to Android version
Building for Apple iOS
Adding the AR Foundation package and GameObjects to a 3D scene
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
Learn more on Discord
Virtual and Extended Reality (VR/XR)
Setting up the Oculus Quest 2 for Unity development
Getting ready
How to do it...
How it works...
There’s more...
Speed up Windows development with Oculus Link/Air Link
Oculus Link is not possible on most Macs
Oculus Link Linux
Online guides to help you set up your Quest for VR development with Unity
Creating and running a Unity project on a VR headset
Getting ready
How to do it...
How it works...
There’s more...
Cannot choose the Quest device due to Android tools unknown location
Build failure due to Android version
Build failure due to “namespace cannot be found” error
Beginning with the XR Interaction Toolkit
Getting ready
How to do it...
How it works...
Creating a 360-degree video VR project
Getting ready
How to do it...
How it works...
Exploring and building the Desert WebXR demo project
How to do it...
How it works...
There’s more...
Fixing pink (shader/material) problems
The OpenUPM community maintains more up-to-date XR resources
Latest releases from De-Panther
Missing packages error
Using GitHub Pages to publish your WebXR project for free
Getting ready
How to do it...
How it works...
Creating a simple WebXR scene from scratch
Getting ready
How to do it...
How it works...
Further reading
Advanced Topics – Gizmos, Automated Testing, and More
Using a gizmo to show the currently selected object in the Scene panel
How to do it...
How it works...
Creating an Editor snap-to-grid drawn by a gizmo
How to do it...
How it works...
There’s more...
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
EditMode minimum skeleton unit test script
Making 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 DataProvider
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
Learn more on Discord
Other Books You May Enjoy
Index
Cover
Index
Once you’ve read Unity Cookbook, Fifth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781805123026
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyA key element that contributes to the entertainment and enjoyment of most games is the quality of the player’s 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.
This chapter is all about the Unity UI system. This is based on GameObjects and their components, and the recommended system for runtime player visual UIs. There are other UI systems in Unity (UI Toolkit and IMGUI), but these are mostly used for Unity Editor design-time interfaces.
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 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 only allows one EventSystem in any scene.Visual UIcontrols: The visible UI controls include Button, Image, TextMeshPro, and Toggle.The Rect Transformcomponent: UI GameObjects are GameObjects that take up a rectangle on a 2D plane, and so have a Rect Transform component rather than a Transform component. The special Rect Transform component has some different properties from the scene’s GameObject Transformcomponent (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 display-only and interactive UI controls, non-visible interactive 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.
Note that UI controls must be a child or descendant of a Canvas, otherwise, theywill not work properly. Also, interactive UI controls will not work properly if the EventSystem GameObject is missing.
Both the Canvas and EventSystem GameObjects are automatically added to the Hierarchy panel as soon as the first UI GameObject is added to a scene:
Figure 1.1: Canvas and EventSystem
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, sized, scaled, and rotated. UI GameObjects have a Pivot Point, indicated in the Scene panel by a small blue circle. All transformations are made relative to this pivot point, for example, rotations of a GameObject are around this point. If a UI GameObject is moved, its pivot point is moved too.
Figure 1.2: Transformations relative to pivot point and anchors
UI GameObjects also have Anchors