A button to play a sound with no scripting
Unity can send messages to GameObjects, including built-in components such as AudioSource and components that are instances of C# script classes we write ourselves. In this recipe, we’ll create a scene with a button that sends a Play()
message to the AudioSource component of a GameObject – to illustrate how some messages can be sent with no custom scripting at all. Then, in the following recipe, we’ll write a custom C# script class that will refine the scene’s behavior, preventing the AudioSource from being restarted if it is already playing.
Getting ready
Try out this recipe with any audio clip that is one second or longer in duration. We have included the engineSound
audio clip inside the 04_09_engine_sound/Sounds/
folder.
How to do it...
To create a button to play a sound with no scripting, perform the following steps:
- Create a new Unity 2D project and import the sound clip file. ...