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

Game options – toggling audio


In this recipe, we will show you how toggle buttons for the user interface of games made with Unity can be created and managed.

Getting ready

Like the previous recipe, you must have the Options Screen scene loaded in the Editor and the GUI script open in Monodevelop.

How to do it...

  1. Let's begin by creating a bool variable to control whether the toggle is on or off. We do this by adding the following declaration at the top of the script:

    private bool toggleAudio = true;
  2. Next, we create the toggle button on the screen by adding the following line inside the OnGUI() function:

    toggleAudio = GUI.Toggle(new Rect(100, 30, 10, 10), toggleAudio, "Toggle Audio");
  3. Now, in the Update() function, we add a line to ensure that the audio is enabled, depending on the toggleAudio value:

    audio.enabled = toggleAudio;
  4. The following screenshot provides the complete GUI script we used for the Options Screen scene: