- Home /
Audio Clip trouble
I have an audio clip that uses AudioSource.PlayClipAtPoint to play when a button is pressed. The button that is pressed makes the scene change, so it only plays part of the audio clip. How would I get the audio clip play fully while still changing scenes (Note: It is only a second or 2 long, I dont want it to keep playing throughout the scene)
Answer by Jeric-Miana · Aug 21, 2014 at 11:45 AM
var yourAudio : AudioSource;
function OnGUI()
{
if(GUI.Button(new Rect(10,10,100,100))
{
audio.Play();
ChangeScene();
}
}
function ChangeScene()
{
yield WaitForSeconds(10);//delay time to finish your sound
//then load a scene
Application.LoadLevel(0);
}
I dont know if this code will help you but i think this will give you an idea to your problem
I have tried using this in csharp but I have no idea how to use yield.
This is the function I added:
void PlayAgain()
{
yield WaitForSeconds(1);
Application.LoadLevel(GameplayLevel);
}
Then I referenced it in the GUI but I have an error saying:
error CS1525: Unexpected symbol (', expecting
)', ,',
;', [', or
='
This error is right after "yield WaitForSeconds"
For coroutine functions in CSharp use:
IEnumerator PlayAgain() { //change type
yield return new WaitForSeconds(1.0f); //change return
Application.LoadLevel(GameplayLevel);
}
I added what you said @zharik86 and now the audio plays but the level never loads and I can just click the button as much as I want
$$anonymous$$ost likely you incorrectly transferred a code to CSharp. I will write the common method. Below I will write a full code which works:
public AudioSource myAudio = null; //reference for your audio if it's not component of this object
//It is possible to make also a variable when pressed the button
//it is impossible to press more if the audio didn't come to an end yet.
private bool goAudio = false;
void OnGUI() {
if (GUI.Button(new Rect(0, 0, 200, 100), "Load level") && !goAudio) {
StartCoroutine(this.myPlayAgain());
}
}
IEnumerator myPlayAgain() {
goAudio = true;
myAudio.Play();
//yield return new WaitForSeconds(1.0f);
//We can find duration of audio and use this value.
yield return new WaitForSeconds(myAudio.clip.length);
Application.LoadLevel(GameplayLevel);
goAudio = false;
}
Answer by bustedkrutch · Aug 21, 2014 at 07:19 PM
The way that I'm handling this is that for AudioClips that need to be played across scenes I play them on an AudioSource that is associated with a script on a GameObject that I've used "DontDestroyOnLoad" with.
In my case (for better or worse) I have a "GameController" that survives across all scene changes. That is where I store my "persistent" data. This allows me to fade in the loading scenes ambient "soundtrack" while fading out the exiting scenes "soundtrack:
Let me know if you would like me to expand on this.