Play Sound on Fire (C#)


I would like to play a gun sound when I click the left mouse button. How should I do this in C#?
With AudioSource or AudioClip?


Any audio needs an audioSource to play. Whether you assign audio in the Inspector, by script with audioClip, PlayOneShot, PlayClipAtPoint.

Which of these methods you use depends on how you want to use the sound. And personal preference or coding style. For a gun firing you could play the audio or PlayOneShot, and for the bullet ricocheting at the point of impact use PlayClipAtPoint.

from : Unity - Manual: Audio Source

You can play a single audio clip using Play, Pause and Stop. You can also adjust its volume while playing using the volume property, or seek using time. Multiple sounds can be played on one AudioSource using PlayOneShot. You can play a clip at a static position in 3D space using PlayClipAtPoint.

But for any Audio , you Need an AudioSource =]

Some reference links :

Here’s a C# example of PlayOneShot : how to add a sound to this script - Questions & Answers - Unity Discussions

And a JS example of changing the audioClip to be played (scroll down to my answer) : how to press key , the object will random to play music and stop music? - Questions & Answers - Unity Discussions

If you need any clarification from all this info, let me know =]

You can try the simple:

AudioSource audio = gameObject.AddComponent < AudioSource > ();

audio.PlayOneShot ((AudioClip)Resources.Load (“gunshot1”));