Book Image

Unity 4.x Cookbook

By : Matt Smith, Chico Queiroz
Book Image

Unity 4.x Cookbook

By: Matt Smith, Chico Queiroz

Overview of this book

<p>Covering the latest version (Unity 4) of this established game engine, the Unity 4.x Cookbook explores a wide range of 3D, animation, multimedia, and scripting game features.<br /><br />The power of Unity 4 is demonstrated through the 10 chapters covering many of this game engine’s features.<br /><br />"Unity 4.x Cookbook" helps you learn how to make the most of the powerful but easy-to-use Unity 4 game engine. <br /><br />Every Unity game developer is different. Some come from a multimedia background, some are new to game development, and some are transferring from other engines. Whatever your background, with the breadth and depth of topics covered you should find new features and techniques to enhance your next game.<br /><br />This book offers detailed, easy-to-follow, step-by-step recipes helping you master a wide range of Unity game features. <br /><br />Chapters are provided focusing on the basics; audio, cameras, images, materials and animations, GUIs, external resources and devices, directional and artificial intelligence character control, and performance optimization.<br /><br />"Unity 4.x Cookbook" provides a collection of ideas and resources that should offer new and useful techniques for every Unity game developer to enhance their next game.</p>
Table of Contents (18 chapters)
Unity 4.x Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Preventing the AudioClip from restarting if already playing


In a game there may be several different events that cause a sound to start playing. If the sound is already playing, then in almost all cases we don't wish to restart the sound. This recipe includes a test, so that an AudioSource component is only sent a Play() message if it is not currently playing.

Getting ready

Try this with any audio clip that is one second or longer in duration.

How to do it...

To prevent an audio clip from restarting, follow these steps:

  1. Create an empty game object named AudioObject, and add an audio source component to this object.

  2. Drag an audio clip file from the Project view to populate the AudioClip parameter of the AudioSource component of AudioObject.

  3. Add the following script class to the Main Camera:

    // file: AvoidSoundRestart.cs
    using UnityEngine;
    
    public class AvoidSoundRestart : MonoBehaviour{
      public AudioSource audioSource;
      
      private void OnGUI(){
        string statusMessage = "audio source - not playing...