x


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.

more ▼

asked Sep 13 '11 at 08:43 PM

imnickb gravatar image

imnickb
258 13 17 21

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Sep 13 '11 at 10:34 PM

aldonaletto gravatar image

aldonaletto
41.5k 16 42 197

Perfect! That's exactly what I was looking for.

Sep 14 '11 at 12:59 AM imnickb
(comments are locked)
10|3000 characters needed characters left

Check out PlayClipAtPoint. It does all the creation and clean-up of the audio source for you.

more ▼

answered Sep 13 '11 at 10:03 PM

Molix gravatar image

Molix
4.8k 17 27 66

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5089
x1029
x302
x83
x55

asked: Sep 13 '11 at 08:43 PM

Seen: 2103 times

Last Updated: Sep 14 '11 at 12:59 AM