Audio.play cutting off as scene changes

Hi I’m very new to coding and need some help with my basic buttons ( gui textures ) so far.

I am using gui textures as buttons for a simple game, attached to these gui textures I have variations of the following code:

public class Play: MonoBehaviour {
	void OnMouseUp() {
		audio.Play();


	Application.LoadLevel("GAME");


}

}

I have an audio source on the gui texture that I want the audio.Play to play, but the scene changes too fast for the clip to play, and wondered what’s the best solution to fixing this ? Thanks for any help in advance.

Your AudioSource is probably disappearing when the new level loads.

Put the AudioSource on a game object with a script that contains this:

DontDestroyOnLoad( gameObject );

http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

But make sure it isn’t a level that you are going to come back to again, otherwise it will create multiples of the same gameObject. If you need to return to that scene, put the gameObject in a loading scene that the game only goes to once. Later, when you need the AudioSource use GameObject.Find()

http://docs.unity3d.com/ScriptReference/GameObject.Find.html

So you want to click the button > finish playing audio > Then change the scene.Use a coroutine to yield until the audioclip is finished playing and then execute “Application.LoadLevel(“GAME”);”

	//To make sure the coroutine is executed only once
	bool LoadingInitiated=false;

	void OnMouseUp()
	{
		if (!LoadingInitiated) 
		{
			StartCoroutine(DelayedLoad());
			LoadingInitiated=true;
		}
	}
	
	IEnumerator DelayedLoad()
	{
		//Play the clip once
		audio.PlayOneShot (Clip);

		//Wait until clip finish playing
		yield return new WaitForSeconds (Clip.length);	

		//Load scene here
		Application.LoadLevel("GAME");
		
	}

You are playing the audio and loading the level.

Play to play, but the scene changes too fast for the clip to play, and wondered what’s the best solution to fixing this ?

Fixing to what? We are not mind readers and can’t guess you exactly you want.

You could:

  • Play the audio and on finish load scene
  • Load scene and on load play audio
  • Audio is playing while scene is loading