Creating just-in-time AudioSource components at runtime through C# scripting
In the previous recipe, for each sound clip that 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 runtime – just when they are needed.
This method is similar to the built-in AudioSource PlayClipAtPoint()
method, but the created AudioSource component is completely under our programmatic control.
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, with users helping each other and posting interesting ways of adding features to games. You can find out more about that post at http://answers.unity3d.com/questions/123772/playoneshot-returns-false-for-isplaying.html.
Getting ready
This recipe adapts the previous one. So, make a...