Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. 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.
Read more about Sinéad Murphy

View More author details
Right arrow

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 and Windows Phone
  • Web: WebGL (and WebXR)
  • Desktop: PC, Mac, and Linux platforms
  • Console: Nintendo Switch, PS5/4/3, Xbox SeriesX/One/360, PlayStation Mobile, PlayStation Vita, and Wii U
  • Virtual Reality (VR)/Augmented Reality (AR): Oculus Quest/2/3/Pro and Rift, Samsung Gear VR, HTC Vive Focus, Google Daydream, Microsoft Hololens, and the Apple Vision Pro

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 150 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 for displaying text and images.

Chapter 2, Responding to User Events for Interactive UIs, teaches you about updating displays, and detecting and responding to user input actions, such as mouseovers. 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 and Advanced UIs, relates to the many games that involve the player collecting items, such as keys to open doors and 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 and 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 at 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 a recipe to create a simple 140 bpm loop manager.

Chapter 5, Textures, Materials, and 3D Objects, contains recipes that will give you a better understanding of how to create, import, and modify 3D objects in Scenes. Recipes for this chapter include controlling how objects look by changing their textures and transparency, as well as creating GameObjects by creating and manipulating geometric primitives such as cubes and spheres.

Chapter 6, Creating 3D Environments with Terrains, contains recipes that will give you a better understanding of how to create and modify the large-scale geography of a Scene using the Unity terrain tools. You’ll learn how to texture and height paint terrains, add holes, trees and vegetation, and also begin to explore the powerful, dynamic, realistic water features possible in HDRP (High Definition Render Pipeline) projects.

Chapter 7, Creating 3D Geometry with ProBuilder, contains recipes that will give you a better understanding of how to create and modify 3D objects within the Unity Editor using the powerful ProBuilder toolkit. As well as the basics of working with geometric meshes, you’ll learn to extrude, texture, and vertex paint objects, gaining the skills to quickly prototype terrains and objects for complex game levels.

Chapter 8, 2D Animation and Physics, introduces some of Unity’s powerful 2D animation and physics features. In this chapter, we present recipes to help you understand the relationships between the different animation elements in Unity, exploring the movement of different parts of the body and the use of sprite-sheet image files that contain sequences of sprite frame pictures. In this chapter, core Unity Animation concepts are presented, including Animation State Machines, Transitions, and Trigger events, as well as clipping via Sprite Masks. In addition, this chapter introduces the use of Tiles and Tilemaps for 2D games.

Chapter 9, Animated Character, focuses on character animation and demonstrates how to take advantage of Unity’s Mecanim animation system. It covers a range of subjects, from basic character setup to controlling character animations with the old and new input systems.

Chapter 10, Saving and Loading Data,explores how games running on devices can benefit from persistent file-based data, and also communication with other networked applications. In this chapter, a range of recipes are presented that illustrate how to save and load data between Scenes, how to read data from text files, how to set up an online, database-driven leaderboard, and how to write Unity games that can communicate with such online systems.

Chapter 11, Controlling and Choosing Positions, presents a range of recipes for 2D and 3D user- 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 12, Navigation Meshes and Agents, explores ways that Unity’s NavMeshes and NavMesh Agents offer for the automation of object and character movement and pathfinding in your games. For example, recipes include ways to make objects follow predefined sequences of waypoints, or be controlled by mouse clicks for point-and-click control.

Chapter 13, Cameras, Lighting, and Visual Effects, presents recipes covering techniques for controlling and enhancing your game’s cameras. It offers solutions to work with both single and multiple cameras, illustrates how to apply post-processing effects, such as vignettes and grainy grayscale videos. The chapter also introduces ways to work with Unity’s powerful Cinemachine components. Other recipes in this chapter introduce visual effects including emissive materials and “cookie” textures, simulating objects casting shadows between the light source and the surfaces lights shine onto.

Chapter 14, Shader Graphs and Video Players, covers two powerful visual components in Unity: Shader Graphs and the Video Player. Both make it easy to add impressive visuals to your games with little or no programming. It includes recipes on how to simulate CCTV playback and download and play an online video, as well as an introduction to applying Shader Graphs in projects. Several recipes are presented for each of these features in this chapter.

Chapter 15, Particle Systems and Other Visual Effects, offers a hands-on approach to both using and repurposing Unity’s particle systems package, and also creating your own particle system from scratch.

Chapter 16, Mobile Games and Apps, provides an overview of and introduction to mobile projects in Unity. Since AR/VR/XR projects are mobile applications, this chapter acts as a foundation for those chapters too (Chapters 17 and 18).

Chapter 17, Augmented Reality (AR), provides an overview of and introduction to AR projects in Unity. The recipes guide you through exploring the Unity AR examples, then creating and configuring your own AR projects.

Chapter 18, Virtual and Extended Reality (VR/XR), provides an overview of and introduction to VR projects in Unity. Recipes include creating and configuring projects for VR, adding content, and building apps and deploying them onto devices or publishing them as WebXR via the web.

Chapter 19, Advanced Topics: Gizmos, Automated Testing, and More, explores a range of advanced topics, including creating your own gizmos to enhance design-time work in the Scene through visual grid guides with snapping. Automated code and runtime testing is also introduced, in addition to different approaches to saving and loading game data, and a final recipe introduces the new Python for Unity package, allowing scripting in the popular Python programming language.

Technical requirements to get the most out of this book

To complete the recipes in this book, there are some things that you will need.

For all chapters, you will need Unity 2023.1 or later, plus one of the following computer systems:

  • Microsoft Windows 10 (64-bit)/GPU: DX10, DX11, and DX12-capable
  • macOS GPU Metal-capable Intel or AMD
    • Mojave 10.14+ / Intel x64 with SSE2 instruction set support
    • Big Sur 11.0 / Apple Silicon M1 or later
  • Linux Ubuntu 20.04 or Ubuntu 18.04 / Gnome desktop running on X11 / GPU: OpenGL 3.2+ or Vulkan-capable Nvidia or AMD

For each chapter, there is a folder in the book’s GitHub repository that contains the asset files you will need; you can find these at https://github.com/PacktPublishing/Unity-2023-Cookbook-Fifth-Edition.

For recipes in some chapters, additional hardware/software will be helpful:

  • Chapter 4, Playing and Manipulating Sounds

To edit and create audio files yourself, you can download and install the free Audacity application for your computer system (Windows/Mac/Linux). You can find it at https://www.audacityteam.org/download/.

  • Chapter 5, Textures, Materials, and 3D Objects

To work with 3D objects in the Blender editor, you can download it for free at www.blender.org.

  • Chapter 10, Saving and Loading Data
    • Since some of the recipes in this chapter make use of web servers and a database, for those recipes, you will require either the PHP 8 language (which comes with its own web server and SQLite database features) or an AMP package.
    • If you are installing the PHP language, refer to the installation guide and download links:
    • If you do want to install a web server and database server application, a great choice is XAMPP. It is a free, cross-platform collection of everything you need to set up a database and web server on your local computer. The download page also contains FAQs and installation instructions for Windows, Mac, and Linux: https://www.apachefriends.org/download.html.
  • Chapter 15, Particle Systems and Other Visual Effects

If you wish to create your own image files, you will also need an image editor, such as Adobe Photoshop, which can be found at www.adobe.com, or GIMP, which is a free alternative and can be found at www.gimp.org/.

  • Chapter 16, Mobile Games and Apps
    • If developing for Android, you’ll need an Android mobile device.
    • If developing for Apple iOS, you’ll need:
  • Chapter 17, Augmented Reality (AR)

To get the most from this chapter’s recipes, you will need an AR device. For this, you can use a dedicated device such as an AR headset, or you can use smartphone apps to begin experiencing AR.

  • Chapter 18, Virtual Reality (VR)

You will need a device to view VR apps. For this, you can use a dedicated device, such as a VR headset like the Meta Quest 1/2/3, Samsung Gear VR, or Apple Vision Pro. If you wish to use a smartphone for VR projects, there are many low-cost devices to choose from, such as Google Cardboard: https://developers.google.com/cardboard.

Download the example code files

You’ll find the chapter figures, recipe assets, and completed Unity projects for each chapter at https://github.com/PacktPublishing/Unity-2023-Cookbook-Fifth-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 at https://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://packt.link/gbp/9781805123026.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The playerInventoryDisplay variable is a reference to an instance object of the PlayerInventoryDisplay class.”

A block of code is set as follows:

public class PlayerInventoryDisplay : MonoBehaviour {
   public Text starText;
   public void OnChangeStarTotal(int numStars) {
         string starMessage = "total stars = " + numStars;
         starText.text = starMessage;
   }
}

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

public class PlayerInventoryDisplay : MonoBehaviour {
   public Text starText;
   public void OnChangeStarTotal(int numStars) {
         string starMessage = "total stars = " + numStars;
         starText.text = starMessage;
   }
}

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this: “In the Inspector panel, set the font of Text-carrying-star to Xolonium-Bold, and set its color to yellow.”

Warnings or important notes appear like this.

Tips and tricks appear like this.

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 customercare@packtpub.com.

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

Share your thoughts

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.

Download a free PDF copy of this book

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:

  1. Scan the QR code or visit the link below

    https://packt.link/free-ebook/9781805123026

  2. Submit your proof of purchase
  3. That’s it! We’ll send your free PDF and other benefits to your email directly
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. 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.
Read more about Sinéad Murphy