Unity 2018 Cookbook - Matt Smith - E-Book

Unity 2018 Cookbook E-Book

Matt Smith

0,0
44,39 €

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

With the help of the Unity 2018 Cookbook, you’ll discover how to make the most of the UI system and understand how to animate both 2D and 3D characters and game scene objects using Unity's Mecanim animation toolsets.
Once you’ve got to grips with the basics, you will familiarize yourself with shaders and Shader Graphs, followed by understanding the animation features to enhance your skills in building fantastic games. In addition to this, you will discover AI and navigation techniques for nonplayer character control and later explore Unity 2018’s newly added features to improve your 2D and 3D game development skills. This book provides many Unity C# gameplay scripting techniques.
By the end of this book, you'll have gained comprehensive knowledge in game development with Unity 2018.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 905

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



Unity 2018 CookbookThird Edition
Over 160 recipes to take your 2D and 3D game development to the next level
Matt Smith
BIRMINGHAM - MUMBAI

Unity 2018 Cookbook Third Edition

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.

Contributor: Chico Queiroz Commissioning Editor: Kunal ChaudhariAcquisition Editor: Shweta PantContent Development Editor: Francis CarneiroTechnical Editor: Ralph RosarioCopy Editor: Safis EditingProject Coordinator: Alinka DiasProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai

First published: June 2013 Second edition: October 2015 Third edition: August 2018

Production reference: 1310818

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78847-190-9

www.packtpub.com

I would like to dedicate this book to my wife Sinéad.
– Matt Smith
mapt.io

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.

Why subscribe?

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

Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.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.packt.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.

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've been developing games and game tools professionally for over 15 years. 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 and Chico 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 2018, Matt has updated the recipes from the previous book and added hundreds of new pages to introduce many of the latest Unity features. These include topics such as Shader Graphs, Virtual-Reality projects, 2D and 360-degree Video Players, Cinemachine, in-game geometry building with ProBuilder, and Unity Technologies'2D and 3D GameKits.

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: https://www.romerogames.ie/

Author of Fungus: http://fungusgames.com

Contributors

About the author

Matt Smithis a computing academic at what will soon become the Technological University of Dublin, Ireland.

Matt started computer programming on a brand new ZX80 and submitted two games for his computing O-level exam. After nearly 10 years as a full-time student on a succession of scholarships, he gained several degrees in computing, including a PhD in computational musicology.

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 Confusion. Matt is a documentation author for the open source Fungus Unity project.

With his children, he studies and teaches tae kwon do, and all three of them are beginning guitar lessons in 2018.

Many thanks to Chico for all his work on the earlier editions of this cookbook - I look forward to working with you again in the future.
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 Justin in Limerick for keeping me sane with snooker and golf breaks over the summer.

About the reviewer

Jate Wittayabundit is a Sr Unity developer at WGames based in Toronto, Canada. He loves puzzle games and animation movies. For many years, he has been working as a Sr/lead game developer for many titles, including children's games, such as Dora, Paw Petrol, and such. He was also an author of Unity 3 and 4 Game Development Hotshot, and a technical reviewer for Unity 4.x Cookbook, Packt Publishing. In his spare time, he loves to paint and work on 3D software, such as Zbrush or 3D Studio Max. He also loves painting and drawing.

I’d like to thank my family for supporting me. Thanks to everyone at Packt who give me the opportunity, and thanks to all the readers.

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Unity 2018 Cookbook Third Edition

Dedication

Packt Upsell

Why subscribe?

Packt.com

Foreword

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

Displaying Data with Core UI Elements

Introduction

The big picture

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

There's more...

The Unity tutorial for animating an analog clock

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

We have to make this text crawl like 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...

Data-driven conversations

Responding to User Events for Interactive UIs

Introduction

The big picture

Creating UI Buttons to move between scenes

How to do it...

How it works...

There's more...

Color tint when mouse pointer is over the button

Animating button properties on mouse-over

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 an Input Field

How to do it...

How it works...

There's more...

Limiting the type of content that can be typed

Toggles and radio buttons via Toggle Groups

Getting ready

How to do it...

How it works...

There's more...

Adding more Toggles and a Toggle Group to implement mutually-exclusive radio buttons

Creating text and image icon UI Dropdown 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 NormalisedPosition(...) method

The CalculateBlipPosition(...) method

The DrawBlip() method

There's more...

Adapt for object heights and opaque obstacles

Inventory UIs

Introduction

The big picture

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 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 display scripted component

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 infer number of inventory slots based on number of GameObjects tagged Star

Add a horizontal scrollbar 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...k

There's more...

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

Playing and Manipulating Sounds

Introduction

The big picture

Future audio features

Playing different one-off sound effects with a single AudioSource component

Getting ready

How to do it...

How it works...

There's more...

Play a sound at a static point in 3D world space

Playing and controlling different sounds each with their 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...

See also

Waiting for the audio to finish playing before auto-destructing an object

Getting ready

How to do it...

How it works...

See also

Creating a metronome through the precise scheduling of sounds with dspTime

Getting ready

How to do it...

How it works...

There's more...

Creating just-in-time AudioSource GameObjects for the basic and accented beats

Creating beat sounds through data rather than AudioClips

Matching the audio pitch to the animation speed

Getting ready

How to do it...

How it works...

There's more...

Changing the Animation/Sound Ratio

Accessing the function from other scripts

Allowing reverse animation (negative speeds!)

Simulating acoustic environments with Reverb Zones

Getting ready

How to do it...

How it works...

There's more...

Attaching the Audio Reverb Zone component to Audio Sources

Making your own Reverb settings

Adding volume control with Audio Mixers

Getting ready

How to do it...

How it works...

There's more...

Playing with Audio Production

See also

Making a dynamic soundtrack with Snapshots

Getting ready

How to do it...

How it works...

There's more...

Reducing the need for multiple audio clips

Dealing with audio file formats and compression rates

Applying Snapshots to background noise

Getting creative with effects

See also

Balancing in-game audio with Ducking

Getting ready

How to do it...

How it works...

See also

Audio visualization from sample spectral data

Getting ready

How to do it...

How it works...

The void Awake() method

The void CreateCubes() method

The void Update() method

The void UpdateCubeHeights() method

The float HeightFromSample(float) method

There's more...

Adding visualizations to a second AudioSource

Try out different FFT (Fast Fourier Transform) 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

Creating Textures, Maps, and Materials

Introduction

Creating and saving texture maps

The big picture

Standard Shader (Specular workflow)

Standard Shader (Metallic workflow)

Other material properties

Resources

Unity samples and documentation

References

Tools

Additional reading

Creating a basic material with Standard Shader (Specular setup)

Getting ready

How to do it...

How it works...

There's more...

Setting the texture type for an image file

Combining the map with color

Adapting a basic material from Specular setup to Metallic

Getting ready

How to do it...

How it works...

Applying Normal maps to a Material

Getting ready

How to do it...

How it works...

Adding Transparency and Emission maps to a material

Getting ready

How to do it...

How it works...

There's more...

Using texture maps with the Transparent Mode

Avoiding issues with the semi-transparent objects

Emitting light over other objects

Highlighting materials at mouse-over

How to do it...

How it works...

There's more...

Collider needed for custom meshes

Mouse Down/Up events – for clicking color

Adding Detail maps to a material

Getting ready

How to do it...

How it works...

Fading the transparency of a material

How to do it...

How it works...

There's more...

Start with keypress and fade in from invisible

Destroy object when fading complete

Using GameObect's alpha as our starting alpha value

Using a coroutine for our fading loop

Shader Graphs and Video Players

Introduction

The big picture

The new Shader Graph tool

Playing videos with the new Video Player

Online references materials

Shader Graph online resources

Video Player online resources

Playing videos by manually adding a VideoPlayer component to a GameObject

Getting ready

How to do it...

How it works...

There's more...

Semi-transparent video and Camera Near Plane

Audio issues and AudioSource solution

Using scripting to control video playback on scene textures

Getting ready

How to do it...

How it works...

There's more...

Ensuring that a movie's prepared before playing it with the prepareCompleted event

Outputting video playback to a Render Texture asset

Ensuring that the movie is prepared before playing with coroutines

Downloading an online video (rather than a clip)

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

Using Sine Time to create a pulsating glow effect

Using the Compile and Show Code button as another way to find exposed property IDs

Using Cameras

Introduction

The big picture

Cinemachine

Creating the basic scene for this chapter

Getting ready

How to do it...

How it works...

Creating a picture-in-picture effect

Getting ready

How to do it...

How it works...

There's more...

Changing the size and location of the picture-in-picture viewport on the screen

Adding further contols for depth-of-field and aspect-ratio

Manually changing Camera viewport properties in the Inspector

See also

Switching between multiple cameras

Getting ready

How to do it...

How it works...

There's more...

Using a single-enabled camera

See also

Making textures from screen content

Getting ready

How to do it...

How it works...

There's more...

Applying your texture to a material

Using your texture as a screenshot

See also

Zooming a telescopic camera

Getting ready...

How to do it...

How it works...

There's more...

Adding a vignette effect when you zoom

Going further with version 2 of the Unity Post Processing Stack

Displaying a minimap

Getting ready...

How to do it...

How it works...

There's more...

Using a UI Mask to make the minimap circular in shape

Hiding player character image at center of minimap and showing triangle marker

Rotating a compass-style image

Making the range of the map larger or smaller

Adapting your minimap to other styles

Creating an in-game surveillance Camera

Getting ready

How to do it...

How it works...

There's more...

Using Post-Processing to add a grainy, grayscale effect to the CCTV

Working with Unity's multi-purpose 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 turtorial

Adam Myhill's Cinemachine blog posts

Read the installed Cinemachine documentation

Letting the player switch to a Cinemachine FreeLook camera

Getting ready

How to do it...

How it works...

Lights and Effects

Introduction

The big picture

Lights

Environment lighting

Emissive materials

Projector

Lightmaps

Light probes

The Lighting settings window

The Light Explorer panel

Cucoloris cookies

Color space (Gamma and Linear)

Further resources

Directional Light with cookie Texture to simulate a cloudy day

Getting ready

How to do it...

How it works...

Creating and applying a cookie texture to a spotlight

Getting ready

How to do it...

How it works...

Adding a custom Reflection map to a scene

Getting ready

How to do it...

How it works...

There's more...

Mapping coordinates

Sharp reflections

Maximum size

Creating a laser aim with a projector

Getting ready

How to do it...

How it works...

There's more...

Limiting the range of the laser with Raycast hit to limit the far clip plane

Further reading

Enhancing the laser aim with a Line Renderer

Getting ready

How to do it...

How it works...

There's more...

Changing the beam color when the Fire key is held down

Setting up an environment with Procedural Skybox and Directional Light

How to do it...

How it works...

There's more...

Setting and rising the sun through scripted rotation of Directional Light

Adding a sun flare

Reflecting surrounding objects with Reflection Probes

Getting ready

How to do it...

How it works...

There's more...

Using Material Emission to bake light from a glowing lamp onto scene objects

Getting ready

How to do it...

How it works...

Lighting a simple scene with Lightmaps and Light Probes

Getting ready

How to do it...

How it works...

There's more...

2D Animation

Introduction

The Big picture

Grids, Tilemaps, and Tile Palettes

The 2D GameKit – bringing 2D tools together

Resources

Flipping a sprite horizontally – the DIY approach

Getting ready

How to do it...

How it works...

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

Copy animation relative to a new parent GameObject

Making a platform start falling once stepped on using a Trigger to move 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

Rule Tiles for intelligent Tile selection

Learning more

Creating a game with the 2D Gamekit

Getting ready

How to do it...

How it works...

There's more...

3D Animation

Introduction

The big picture

Configuring a character's Avatar and idle animation

Getting ready

How to do it...

How it works...

There's more...

Use Controller with another 3D character Avatar

See also

Moving your character with root motion and Blend Trees

Getting ready

How to do it...

How it works...

There's more...

Mixing animations with Layers and Masks

Getting ready

How to do it...

How it works...

There's more...

Override versus Additive blending

Organizing States into Sub-state Machines

Getting ready

How to do it...

How it works...

Transforming the Character Controller via scripts

Getting ready

How to do it...

How it works...

Adding rigid props to animated characters

Getting ready

How to do it...

How it works...

There's more...

Removing props with a script

Setting Active if there's only one type of Prop

Using Animation Events to throw an object

Getting ready

How to do it...

How it works...

Applying Ragdoll physics to a character

Getting ready

How to do it...

How it works...

There's more...

Using a new player GameObject rather than deactivating and moving to a respawn point

Rotating the character's torso to aim a weapon

Getting ready

How to do it...

How it works...

There's more...

Generic solution for Cameras other than the Main Camera

Creating geometry with Probuilder

Getting ready

How to do it...

How it works...

Creating a game with the 3D Gamekit

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

Information sources about importing models and animations into Unity

Webserver Communication and Online Version-Control

Introduction

The Big Picture

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

Unity game communication with 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 the secret game codes to secure your leaderboard scripts

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 about GitHub for Unity

Pulling down updates from other developers

Unity Collaborate from Unity Technologies

Preventing your game from running on unknown servers

Getting ready

How to do it...

How it works...

There's more...

Enabling WebGL in Google Chrome

Improving security by using full URLs in your domain list

Controlling and Choosing Positions

Introduction

The big picture

Player control of a 2D GameObject (and limiting the movement within a rectangle)

Getting ready

How to do it...

How it works...

There's more...

Drawing a gizmo yellow rectangle to visually show bounding a rectangle

See also

Player control of a 3D GameObject (and limiting the movement within a rectangle)

How to do it...

How it works...

There's more...

Drawing a gizmo yellow rectangle to visually show bounding a 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...

Navigation Meshes and Agents

Introduction

The big picture

Run-Time Nav Mesh Obstacles

Source of further information about Unity and AI navigation

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 NavMeshAgent destination to flee from Player's current location

Maintain constant distance from target ("lurking" mode!)

Point-and-click move to object

Getting ready

How to do it...

How it works...

There's more

Creating a mouse-over yellow highlight

Point-and-click move to tile

Getting ready

How to do it...

How it works...

There's more

Yellow debug-ray to show destination of 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 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 a 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...

Design Patterns

Introduction

The big picture

State-driven behavior DIY states

How to do it...

How it works...

See also

State-driven behavior using the State Design Pattern

Getting ready

How to do it...

How it works...

There's more...

Adding the Timer event to lose the game after five seconds

See also

State-driven behavior with Unity Scriptable Objects

How to do it...

How it works...

There's more...

Extending the game to model Player health

See also

Publisher-Subscriber pattern C# delegates and events

Getting ready

How to do it...

How it works...

Model-View-Controller (MVC) pattern

Getting ready

How to do it...

How it works...

See also

Editor Extensions and Immediate Mode GUI (IMGUI)

Introduction

The Big picture

Unity Immediate Mode GUI (IMGUI)

Identifying and saving changes

Memory - EditorPrefs persistent storage

Conclusions and further resources

Menu items to log messages and clear the console

How to do it...

How it works...

There's more

Keyboard shortcuts

Sub-menus

Displaying a panel with text data

How to do it...

How it works...

There's more

Vertical centering

Vertical and horizontal centering (middle of an area)

An interactive panel with persistent storage

How to do it...

How it works...

There's more

Persistent storage with EditorPrefs

GUILayout versus EditorGUILayout

Creating GameObjects, parenting, and registering Undo actions

How to do it...

How it works...

There's more

Registering object changes to allow Undo'ing of actions

Creating primitive 3D GameObjects with random colors

Working with selected objects and deactivating menu items

How to do it...

How it works...

Menu item to create 100 randomly positioned prefab clones

Getting ready

How to do it...

How it works...

There's more...

Childing each new GameObject to a single parent, to avoid filling up the Hierarchy with 100s of new objects

A progress bar to display proportion completed of Editor extension processing

Getting ready

How to do it...

How it works...

An editor extension to allow pickup type (and parameters) to be changed at design time via a custom Inspector UI

Getting ready

How to do it...

How it works...

There's more...

Offer the custom editing of pickup parameters via Inspector

Offer a drop-down list of tags for key-pickup to fit via Inspector

Logic to open doors with keys based on fitsLockTag

The need to add [SerializeField] for private properties

An editor extension to have an object-creator GameObject, with buttons to instantiate different pickups at cross-hair object location in scene

Getting ready

How to do it...

How it works...

Extensible class-based code architecture to manage complex IMGUIs

How to do it...

How it works...

Script-class MyEditorWindow

Script-class IMyGUI

Script-class MyGUIFlexibleSpace

Script-class MyGUITextField

Script-class MyGUILabel

Script-class MyGUIButton

Working with External Resource Files and Devices

Introduction

The big picture

Loading external resource files – using Unity Default Resources

Getting ready

How to do it...

How it works...

There's more...

Loading text files with this method

Loading and playing audio files with this method

See also

Loading external resource files by downloading files from the internet

Getting ready

How to do it...

How it works...

There's more...

Converting from Texture to Sprite

Downloading a text file from the web

The WWW class and the resource content

An example using UnityWebRequest

See also

Loading external resource files by manually storing files in the Unity 
Resources or StreamingAssets folders

Getting ready

How to do it...

How it works...

There's more...

Avoiding cross-platform problems with Path.Combine() rather than / or \

SteamingAssets folder

See also

Saving Project files into Unity Asset Bundles

Getting ready

How to do it...

How it works...

Loading resources from Unity Asset Bundles

Getting ready

How to do it...

How it works...

There's more...

Loading AssetBundles via AssetBundle.LoadFromFile()

Loading AssetBundles hosted via a web server

Working with Plain Text, XML, and JSON Text Files

Introduction

The Big picture

XML – the eXtensible markup language

JSON – the JavaScript object notation

Loading external text files using the TextAsset public variable

Getting ready

How to do it...

How it works...

Loading external text files using C# file streams

Getting ready

How to do it...

How it works...

Saving external text files with C# file streams

Getting ready

How to do it...

How it works...

There's more...

Choosing the Data or the Resources folder

Loading and parsing external XML

Getting ready

How to do it...

How it works...

There's more...

Retrieving XML data files from the web

Creating XML text data manually using XMLWriter

How to do it...

How it works...

There's more...

Adding new lines to make XML strings more human readable.

Making data class responsible for creating XML from list

Saving and loading XML text data automatically through serialization

Getting ready

How to do it...

How it works...

There's more...

Defining the XML node names

Loading data objects from XML text

Creating XML text files – saving XML directly to text files with XMLDocument.Save()

How to do it...

How it works...

Creating JSON strings from individual objects and lists of objects

How to do it...

How it works...

Creating individual objects and Lists of objects from JSON strings

How to do it...

How it works...

Virtual Reality and Extra Features

Introduction

The Big picture

Virtual reality

Gizmos

Saving/Loading data at runtime

Saving screenshots from the game

Getting ready

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

UI Slider to change game quality settings

Getting ready

How to do it...

How it works...

There's more...

Seeing/editing the list of quality settings

Pausing the game

Getting ready

How to do it...

How it works...

There's more...

Learning more about quality settings

Offering the user further game settings

Implementing slow motion

Getting ready

How to do it...

How it works...

There's more...

Customizing the slider

Adding Motion Blur

Creating sonic ambience

Using Gizmo to show the currently selected object in a scene panel

How to do it...

How it works...

Editor snap-to grid drawn by Gizmo

How to do it...

How it works...

Creating a VR project

Getting ready

How to do it...

How it works...

There's more...

Exploring free VR/XR samples/tutorials

Setup with Oculus Rift

Using a Single Pass if working with the Lightweight Rendering Pipeline

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

Working with VR content inside a VR environment – the XR Editor

Getting ready

How to do it ...

How it works...

Automated Testing

Introduction

The big picture

Unit tests

Integration tests (PlayMode tests in Unity)

Generating a default test script class

How to do it...

How it works...

There's more...

Create a default test script from the Project panel'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 method

How to do it...

How it works...

Unit testing a simple health script class

How to do it...

How it works...

Script-class Health.cs

Script-class TestHealth.cs

Creating and executing a unit test in Play mode

How to do it...

How it works...

PlayMode testing a door animation

Getting ready

How to do it...

How it works...

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

Bonus Chapters

Working with External Resource Files and Devices

Working with Plain Text, XML, and JSON Text Files

Virtual Reality and Extra Features

Automated Testing

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Game development is a broad and complex task. It is an interdisciplinary field, covering subjects as diverse as artificial intelligence, character animation, digital painting, and sound editing. All these areas of knowledge can materialize as the production of hundreds (or thousands!) of multimedia and data assets. A special software application—the game engine—is required to consolidate all these assets into a single product. Game engines are specialized pieces of software, which used to belong to an esoteric domain. They were expensive, inflexible, and extremely complicated to use. They were for big studios or hardcore programmers only. Then, along came Unity.

Unity represents the true democratization of game development. It is an engine and multimedia editing environment that is user-friendly and versatile. It has free and Pro versions; the latter includes even more features. Unity offers deployment to many platforms, including the following:

Mobile:

Android, iOS, Windows Phone, and BlackBerry

Web:

WebGL

Desktop:

PC, Mac, and Linux platforms

Console:

PS4, PS3, Xbox One, XBox 360, PlayStation Mobile, PlayStation Vita, and Wii U

Virtual Reality

(

VR

)/

Augmented Reality

(

AR

): Oculus Rift, Gear VR, Google Daydream, and Microsoft Hololens

Today, Unity is used by a diverse community of developers all around the world. Some are students and hobbyists, but many are commercial organizations, ranging from garage developers to international studios, who use Unity to make a huge number of games—you might have already played some on one platform or another.

This book provides over 170 Unity game development recipes. Some recipes demonstrate Unity application techniques for multimedia features, including working with animations and using preinstalled package systems. Other recipes develop game components with C# scripts, ranging from working with data structures and data file manipulation to artificial intelligence algorithms for computer-controlled characters.

If you want to develop quality games in an organized and straightforward way, and you want to learn how to create useful game components and solve common problems, then both Unity and this book are for you.

Who this book is for

This book is for anyone who wants to explore a wide range of Unity scripting and multimedia features and find ready-to-use solutions for many game features. Programmers can explore multimedia features, and multimedia developers can try their hand at scripting. From intermediate to advanced users, from artists to coders, this book is for you, and everyone in your team! It is intended for everyone who has the basics of using Unity and a little programming knowledge in C#.

What this book covers

Chapter 1, Displaying Data with Core UI Elements, is filled with User Interface (UI) recipes to help you increase the entertainment and enjoyment value of your games through the quality of the visual elements displaying text and data. You'll learn a wide range of UI techniques, including displaying text and images, 3D text effects, and an introduction to displaying text and image dialogues with the free Fungus package.

Chapter 2, Responding to User Events for Interactive UIs, teaches you about updating displays (for example basic on timers), and detecting and responding to user input actions, such as mouseovers, while the first chapter introduced code UI for displaying values to the user. Among other things, there are recipes for panels in visual layers, radio buttons and toggle groups, interactive text entry, directional radars, countdown timers, and custom mouse cursors.

Chapter 3, Inventory UIs, relates to the many games that involve the player collecting items, such as keys to open doors, ammo for weapons, or choosing from a selection of items, such as from a collection of spells to cast. The recipes in this chapter offer a range of text and graphical solutions for displaying inventory status to the player, including whether they are carrying an item or not, or the maximum number of items they are able to collect.

Chapter 4, Playing and Manipulating Sounds, suggests ways to use sound effects and soundtrack music to make your game more interesting. The chapter demonstrates how to manipulate sound during runtime through the use of scripts, Reverb Zones, and the Audio Mixer. It also includes recipes for real-time graphics visualizations of playing sounds and ends with a recipe to create a simple 140 bpm loop manager, with visualizations of each playing loop.

Chapter 5, Creating Textures, Maps and Materials, contains recipes that will give you a better understanding of how to use maps and materials with the Physically-Based Shaders, whether you are a game artist or not. It's a great resource for exercising your image editing skills.

Chapter 6, Shader Graphs and Video Players, covers two recent visual components that Unity has added: Shader Graphs and the Video Player. Both make it easy to add impressive visuals to your games with little or no programming. Several recipes are presented for each of these features in this chapter.

Chapter 7, Using Cameras, presents recipes covering techniques for controlling and enhancing your game's camera(s). It offers solutions to work with both single and multiple cameras, illustrates how to apply Post-Processing effects, such as vignettes and grainy gray-scale CCTVs. The chapter concludes by introducing ways to work with Unity's powerful Cinemachine components.

Chapter 8, Lights and Effects, offers a hands-on approach to several of Unity's lighting system features, such as cookie textures, Reflection maps, Lightmaps, Light and Reflection probes, and Procedural Skyboxes. Also, it demonstrates the use of Projectors.

Chapter 9, 2D Animation, introduces some of Unity's powerful 2D animation and physics features. In this chapter, we will present recipes to help you understand the relationships between the different animation elements in Unity, exploring both the movement of different parts of the body and the use of sprite-sheet image files that contain sequences of sprite frames pictures. In this chapter core, Unity Animation concepts, including Animation State Charts, Transitions, and Trigger events, are also introduced. Finally, 2D games often make use of Tiles and Tilemaps (now features that are part of Unity), and these features, as well as the Unity 3D Gamekit, are all introduced in the recipes of this chapter.

Chapter 10, 3D Animation, focuses on character animation and demonstrates how to take advantage of Unity's animation system—Mecanim. It covers a range of subjects, from basic character setup to procedural animation and ragdoll physics. It also offers introductions to some of the newer Unity 3D features, such as Probuilder and the Unity 3D Gamekit.

Chapter 11, Webserver Communication, and Online Version Control, explores how games running on devices can benefit from communication with other networked applications. In this chapter, a range of recipes are presented, which illustrate how to set up an online, database-driven leaderboard, how to write Unity games that can communicate with such online systems, and ways to protect your games from running on unauthorized servers (to prevent your WebGL games being illegally copied and published on other people's servers. In addition, the recipes illustrate how to structure your projects so that they can be easily backed up using online version control systems such as GitHub, and also how to download projects from online sites to edit and run on our own machine.

Chapter 12, Controlling and Choosing Positions, presents a range of recipes for 2D and 3D users and computer-controlled objects and characters, which can lead to games with a richer and more exciting user experience. Examples of these recipes include spawn points, checkpoints, and physics-based approaches, such as applying forces when clicking on objects and firing projectiles into the scene.

Chapter 13, Navigation Meshes and Agents, explores ways that Unity's Nav Meshes and Nav Mesh Agents offer for the automation of object and character movement and pathfinding in your games. Objects can follow predefined sequences of waypoints, or be controlled by mouse clicks for point-and-click control. Objects can be made to flock together based on the average location and movement of all members of their flock. Additional recipes illustrate how the "cost" of navigation areas can be defined, simulating hard-to-travel areas such as mud and water. Finally, although much navigation behavior is pre-calculated at Design Time (the "baking" process), a recipe is presented illustrating how movable objects can influence path-finding at runtime through the use of the NavMesh Obstacle component.

Chapter 14, Design Patterns, illustrates software design patterns that are reusable, and computer-language independent templates for how to solve common problems. It teaches to avoid reinventing the wheel, learn about tried-and-tested approaches to solving common features for game projects. This chapter introduces several design patterns relevant to games, including the State pattern, the publisher-subscriber pattern, and the model-view-controller pattern.

Chapter 15, Editor Extensions and Immediate Mode GUI (IMGUI), provides several recipes for enhancing design-time work in the Unity Editor. Editor Extensions are scripting and multimedia components, which allow working with custom text, UI presentation of the game parameters, data in the Inspector and Scene panels, and custom menus and menu items. These can facilitate workflow improvements, allowing game developers to achieve their goals quicker and easier. Some of the recipes in this chapter include menu items, interactive panels with persistent storage, registering actions for the Undo system, deactivating menu items, progress bars, and ways to create new GameObjects based on prefabs.

To get the most out of this book

All you need is a copy of Unity 2018, which can be downloaded for free from http://www.unity3d.com. If you wish to create your own image files, for the recipes in the Creating Maps and Materials, for example, you will also need an image editor, such as Adobe Photoshop, which can be found at http://www.photoshop.com, or GIMP, which is free and can be found at http://www.gimp.org.

Download the example code files

You'll find the recipes assets and completed Unity projects for each chapter at: https://github.com/PacktPublishing/Unity-2018-Cookbook-Third-Edition.

You can either download these files as Zip archives or use free Git software to download (clone) these files. These GitHub repositories will be updated with any improvements.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

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/Unity2018CookbookThirdEdition_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.packt.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.

Reviews

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

Displaying Data with Core UI Elements

In this chapter, we will cover:

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

Introduction

A key element contributing 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.

The big picture

Every game 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 the Unity 2018 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 elements can be used for a variety of purposes so that you can 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.

The basic UI elements 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 progress bars or radar screens).

Core GameObjects, components, and concepts relating to Unity UI development include:

Canvas

: Every UI element is a child

to 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 to 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 themselves include

B

utton

,

Image

,

Text

,

and

Toggle

.

The

Rect Transform

component

: UI GameObjects can exist in a different space from

that of the 2D and 3D scenes, which cameras render. Therefore, UI GameObjects all have 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. Note that UI controls that are not a child or descendant of a Canvas will not work properly, and interactive UI controls will not work properly if the EventSystem is missing. Both the Canvas and EventSystem GameObjects are automatically added to the Hierarchy as soon as the first UI GameObject is added to a scene:

Rect Transformsfor 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 the 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 of the rectangle. However, if the anchors are not all at the same point, Canvas resizing will result in stretching the element's rectangle. So instead of the Width, we'll seethe values for Left and Right—the position of the horizontal sides of the rectangle to the sides of the Canvas, where the Width will depend on the actual Canvas width (and the same for Top/Bottom/Height).