Playing Audio clip

I want to know what is wrong with this code. What I am trying to do is to play an AudioClip when clicked on button. Button loads another scene.

var beep: AudioClip;
function OnMouseDown() [
audio.PlayOneShot(beep);
yield new WaitForSeconds(2);

function OnGUI() {

if (GUI.Button (Rect (buttonOrigin,110,150,50), “New Game”)) {

Application.LoadLevel (“Main”);
}
}

When I click on New Game I dont hear the sound. And yes I have connected sound through Unity. I imported sound clip into unity and then connected it through inspector.

Thanks

Hello,

As far as I can see:

function OnMouseDown() [
audio.PlayOneShot(beep);
yield new WaitForSeconds(2);

Are you sure you are getting this event when you place your mouse under your button?, why dont play the audio inside the button logic?

You mean this?

if (GUI.Button (Rect (buttonOrigin,110,150,50), “New Game”)) {
audio.PlayOneShot(beep);
yield new WaitForSeconds(2); // cannot use yield as guis dont like coroutines and if I eliminate this , nothing happens , even level does not get loaded
Application.LoadLevel (“Main”);
}

when
put this statement inside OnGUI()
print(beep.length) I do get the length of audio clip which is attached to beep variable and its also ready to play… but it just wont play it…

Any thoughts?

The problem is that when you call Application.LoadLevel, the new level starts loading straight away and so you don’t hear the sound play first.

You can use MonoBehaviour.Invoke to call a named function after a time delay. Put your call to Application.LoadLevel in a function and use Invoke to call it after a short delay equal to the length of the sound you want to play:-

if (GUI.Button (Rect (buttonOrigin,110,150,50), "New Game")) { 
    audio.PlayOneShot(beep);
    Invoke("NewLevelFunc", beep.length);
}

function NewLevelFunc() {
    Application.LoadLevel ("Main"); 
}

Hello Andeee,

That worked and indeed invoke() is a powerful function.

Thanks,