- Home /
Play sound on button press?
I have wrote this script which I think is supposed to play a sound when the LMB is pressed, but I have lots of errors which I'm guessing means this script isn't possible. Can any take a look and help me out?
function Update () {
if(Input.GetButtonDown("Fire1")){
audio.Play("sniper rifle gunshot");
}
}
It's totally possible and easy. Please post your code so we can see what's gone wrong.
Answer by aldonaletto · Nov 03, 2011 at 10:09 PM
audio.Play() only plays the sound assigned to audio.clip - you can't pass the file name. The object to which this script is attached must have an AudioSource, and the sound must be imported with menu option Assets/Import New Asset... and assigned to the AudioSource clip property (Audio Clip, in the Inspector).
If you have different sounds to play in the same object, you can change the clip property and use Play, or use PlayOneShot(sound), where sound is an AudioClip variable.
Use audio.Play without any arguments:
audio.Play(); // play the current audio.clip AudioClip
Or define the AudioClip variables and play one of them with audio.PlayOneShot:
var sound1: AudioClip; // drag the sound 1 here
var sound2: AudioClip; // drag the sound 2 here
...
audio.PlayOneShot(sound1);
do you mean like this because I have an error saying "no appropriate version of unityengine.audiosource.play for the argument list (string) was found" I have no idea what this means this is the script.
var sound : AudioClip;
function Update (){
if(Input.GetButtonDown("Fire1")){
audio.Play("sniper rifle gunshot");
}
}
That's what I said above: Play doesn't accept a file name - define the sound in the AudioSource at the Inspector and use just Play(), without any argument. An alternative is to use an AudioClip variable and play it with PlayOneShot. The example below show both cases - use only one of them and delete the other!:
var sound : AudioClip; // drag the sound here
function Update (){ if(Input.GetButtonDown("Fire1")){ // you can use PlayOneShot to specify the sound... audio.PlayOneShot(sound); // or you can define the sound in the Inspector // and use Play like this: audio.Play(); } }
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Screetching Sound While Walking? Why? 0 Answers
Play sound, while press any key 3 Answers