- Home /
Answer by AlucardJay · Jul 25, 2012 at 01:22 PM
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 : http://docs.unity3d.com/Documentation/Components/class-AudioSource.html
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 :
http://docs.unity3d.com/Documentation/ScriptReference/AudioSource.html
http://docs.unity3d.com/Documentation/ScriptReference/AudioClip.html
http://docs.unity3d.com/Documentation/ScriptReference/AudioSource.PlayOneShot.html
http://docs.unity3d.com/Documentation/ScriptReference/AudioSource.PlayClipAtPoint.html
Here's a C# example of PlayOneShot : http://answers.unity3d.com/questions/278058/how-to-add-a-sound-to-this-script.html
And a JS example of changing the audioClip to be played (scroll down to my answer) : http://answers.unity3d.com/questions/250261/press-key-p-the-object-will-random-to-play-music.html
If you need any clarification from all this info, let me know =]
Answer by kwokman · May 29, 2015 at 09:13 AM
You can try the simple:
AudioSource audio = gameObject.AddComponent < AudioSource > ();
audio.PlayOneShot ((AudioClip)Resources.Load ("gunshot1"));
error CS0236: A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.gameObject'