- Home /
Play Sound when GUI button is pressed.
Hello, I am trying to have a quick sound play when I press a GUI Button Here is the script that I have for the GUI buttons. Is there an easy way to attach a sound to each button.
var model : GameObject;
function OnGUI () {
//background box GUI.Box (Rect (10,130,100,90), "Sounds");
//Make first button if (GUI.Button (Rect(20,160,80,20), "Go")){
}
//Make second button if (GUI.Button (Rect(20,190,80,20), "Stop")){
} }
Answer by jashan · Aug 30, 2010 at 01:39 PM
It is in fact very simple: All you need to do is attach an AudioSource to the same game object (or any other game object), provide a "slot" for that audio source, e.g.
var audio : AudioSource;
And then call
audio.PlayOneShot(audio.clip);
in your if-blocks. If you want multiple sounds, simply create one game object with relevant audiosources attached for each sound you want to play (and create var audio1 : AudioSource; and so on, or use names that actually will tell you what the sound means).
Answer by Quest · Sep 30, 2010 at 05:54 PM
uhmm got a little problem where to place the audio.PlayOneShot(audio.clip); ??? please help this sad guest
Answer by devilkkw · Sep 30, 2010 at 06:05 PM
var model : GameObject; var track : AudioSource;
function OnGUI () {
//background box GUI.Box (Rect (10,130,100,90), "Sounds");
//Make first button if (GUI.Button (Rect(20,160,80,20), "Go")){ audio.clip = track; audio.loop = false;
audio.Play();
}
//Make second button if (GUI.Button (Rect(20,190,80,20), "Stop")){
audio.Stop();
} }
Answer by Quest · Oct 04, 2010 at 05:00 PM
uhm really thanks but... i got a error and i dont know what to do can you help me ?
Assets/side-scroller/Scripts/GUI Options Button.js(40,25): BCE0022: Cannot convert 'UnityEngine.AudioSource' to 'UnityEngine.AudioClip'
what to do ?
here's what I did:
var model : GameObject; var track : AudioClip;
function OnGUI () {
//background box GUI.Box (Rect (10,130,100,90), "Sounds"); //$$anonymous$$ake first button if (GUI.Button (Rect(20,160,80,20), "Go")){ audio.loop = false;
audio.PlayOneShot(track);
} //$$anonymous$$ake second button if (GUI.Button (Rect(20,190,80,20), "Stop")){ audio.Stop(); } }
I added a component which is Audio Source to the main camera, dragged my mp3 to the track variable and I also dragged this one to the AudioClip slot. It worked but my editor log returns this message: $$anonymous$$issingComponentException: There is no 'AudioSource' attached to the "$$anonymous$$ain Camera" game object, but a script is trying to access it. You probably need to add a AudioSource to the game object "$$anonymous$$ain Camera". Or your script needs to check if the component is attached before using it.
Your answer
Follow this Question
Related Questions
play an audio clip from a GUI button 1 Answer
Play sound on button click before loading level. 3 Answers
Making sounds wait for each other to finish 2 Answers
Random, 3d sound. 1 Answer