Symptoms
- I have lots of AudioClips that I want to play from one audio source.
Cause
You have a GameObject in your game that you want to play a variety of sounds on simultaneously. You are able to attach empty GameObjects to the main GameObjects and set each one as an Audio Source to play the sounds, but you want to know if there is an easier way to achieve this without creating multiple child GameObjects.
Resolution
You can attach several Audio Sources to the same GameObject in the Inspector, and get them to play at the same time by calling PlayOneShot(); in a script.
You need the Audio Source attached to your main GameObject and then attach a script to the Audio Source. You can call the script to play multiple AudioClips in the following way:
When you have created this script you will be able to drag your required AudioClips into the relevant script components.
More Information
For more information on calling AudioSource.PlayOneShot(); then see this document here
Comments
8 comments
Cool , thank you !
How and why does this work?
What are the costs of doing this?
And why do you cache a reference (seemingly unnecessarily) to the AudioSource?
@Deeds To answer your last question: you use GetComponents<AudioSource> to retrieve all AudioSource instances, from which you can then extract the relevant audio clips. Not sure why this isn't shown in the code example though. You might find this more helpful: https://answers.unity.com/questions/175995/can-i-play-multiple-audiosources-from-one-gameobje.html
Sorry, I still don't see how the reference is being used.
Nor how this works.
Is the code example completely wrong? It seems like it is.
It's outdated. You'd maybe do something like this:
argh. THANK YOU!
This is almost exactly what I'm doing... and I kind of felt like it was overkill to have an AudioSource for every single AudioClip, so went hunting for ways to play multiple clips at the same time, through one AudioSource.
Which lead me to here, and confusion.
Seems there really is just a one:one ratio between AudioSources and AudioClips.
Again. Thank you. Your way seems better than mine... an ARRAY! I'll try it.
The code example is either wrong or outdated because according to the Scripting API, .PlayOneShot() is called on an AudioSource not an AudioClip.
https://docs.unity3d.com/ScriptReference/AudioSource.PlayOneShot.html?_ga=2.233915998.1929434097.1569861847-1592633089.1569617611
Hello,
I want one empty game object to trigger 8 separate audio sources which are in a circle around the player. How do I do this? I am not very good at programming. I want the player to walk into the middle of room and then trigger the sounds. And then when they leave the sound stops.
Many thanks!
Article is closed for comments.