- Home /
Do I have to create an audio source component to play a sound from script?
I want to play sounds from a script that's attached to a prefab. I'm confused because it seems like to do something like this:
var RumbleSound : AudioClip;
function Start()
{
audio.PlayOneShot(RumbleSound);
}
I have to add an audio source component to the prefab that the script is attached to. There doesn't have to a clip loaded in the audio source, but I definitely have to make an audio source.
I need to be able to add several sounds to the script, which is why I'm not just playing audio from the audio source itself.
Answer by aldonaletto · Sep 13, 2011 at 10:34 PM
There are three ways to play a sound:
1- Play(), which plays the sound currently stored in the AudioSource clip property (requires an AudioSource). You can declare several AudioClip variables or an AudioClip[] array, fill them at the Inspector, assign the sound you want to audio.clip and call audio.Play();
2- PlayOneShot(clip, vol), which plays the sound clip with volume vol - still requires an AudioSource. You can use the same procedure above to define the sounds, but there's no need to use the clip property, since you pass the AudioClip as a parameter;
3- PlayClipAtPoint(clip, point, vol), as @Molix suggested. You don't need an AudioSource because this function creates a temporary instance and kill it right after. It's useful when you don't want to create an AudioSource, or if you want the sound to play at a specific location;
NOTE: Only Play() affects and is affected by the audio source variables (pitch, isPlaying, loop etc.). If you need to change any of these characteristics or check isPlaying, use Play.
Answer by Molix · Sep 13, 2011 at 10:03 PM
Check out PlayClipAtPoint. It does all the creation and clean-up of the audio source for you.