Book Image

Unity 2D Game Development Cookbook

By : Claudio Scolastici
Book Image

Unity 2D Game Development Cookbook

By: Claudio Scolastici

Overview of this book

<p>Unity is a powerful game development engine that provides rich functionalities to create 2D and 3D games.</p> <p>Unity 2D Game Development Cookbook is a practical guide to creating games with Unity. The book aims to serve the purpose of exploring problematic concepts in Unity for 2D game development, offering over 50 recipes that are easy to understand and to implement, thanks to the step-by-step explanations and the custom assets provided. The practical recipes provided in the book show clearly and concisely how to do things right in Unity. By the end of this book, you'll be near "experts" when dealing with Unity. You will also understand how to resolve issues and be able to comfortably offer solutions for 2D game development.</p>
Table of Contents (15 chapters)
Unity 2D Game Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Coding audio


With the Audio Source attached to the collectible prefab, the obvious idea would be to play the sound when a collision occurs between the character and the item.

This can be done by adding a few lines to the Runner script.

In the OnCollisionEnter() function of the script, we write this if statement to check whether the character hit a collectible:

if(c.gameObject.tag == "collectible"){
  Destroy(c.gameObject);
  collected += 1;
  Debug.Log(collected);
}

If we want the audio clip to be played when the character collides with a collectible, we can apparently put the following line inside the if() statement:

c.gameObject.audio.Play();

Unfortunately, we can't do that! If we did, the collectible game object would be destroyed the very moment it begins playing the sound, and the player would hear nothing.

This is a common problem, but there are many solutions to overcome it. The solution we provide is a creative way to achieve the result we want, and it involves using another important Unity...