Creating just-in-time AudioSource components at runtime through C# scripting
In the previous recipe, for each sound clip we wanted to manage, in the scene we had to manually create GameObjects with AudioSource components at Design-Time. However, using C# scripting, we can create our own GameObjects that contain AudioSources at Run-Time, just when they are needed. This method is similar to the built-in AudioSourcePlayClipAtPoint() method, but the created AudioSource component is completely under our programmatic control – although we then have to be responsible for destroying this component when it is no longer needed.
Note
This code was inspired by some of the code posted in 2011 in the online Unity Answers forum by user Bunny83. Unity has a great online community helping each other and posting interesting ways of adding features to games. Learn more about that post at http://answers.unity3d.com/questions/123772/playoneshot-returns-false-for-isplaying.html.
Getting ready
This recipe adapts the...