Steven
Steven

Reputation: 45

Unity sound not playing

I'm trying to play a sound, but it's not playing

Here's my code:

public void Replay()
{
  playAudio ();
  Application.LoadLevel (Application.loadedLevel);
}

void playAudio()
{
    AudioSource audio = GetComponent<AudioSource> ();

    audio.Play();
}

When a button clicked, I'm calling Replay(). But, the sound is not played.

If I remarkedApplication.LoadLevel (Application.loadedLevel);, the sound plays normally.

What should I do to make the sound play with Application.LoadLevel()?

Upvotes: 4

Views: 1843

Answers (3)

Mattias
Mattias

Reputation: 3907

The AudioSource playing the sound will get removed before it has time to finish.

Here is an alternative solution using yield to wait for the sound to finish.

public void Replay()
{
    StartCoroutine("ReplayRoutine");
}

IEnumerator ReplayRoutine()
{
    AudioSource audio = GetComponent<AudioSource>();

    audio.Play();
    yield return new WaitForSeconds(audio.clip.length);

    Application.LoadLevel(Application.loadedLevel);
}

Upvotes: 1

Sean Ed-Man
Sean Ed-Man

Reputation: 378

I think you don't give the chance to the audio source to play the sound, because after executing play, you immediately re-loaded the scene, so the same instance of audio source does not exist anymore, a new instance is created which has not yet received the play command. You can use some small delay using co-routine or other ways to give the needed time to the audio source. ( If you want to play the sound before loading level, otherwise just play the sound in a Start() callback)

Upvotes: 0

kagkar
kagkar

Reputation: 469

You call play method and you load the scene after it. Try to call playAudio() before loading level.

public void Replay() {
    Application.LoadLevel(Application.loadedLevel);
    playAudio();
}

Upvotes: 0

Related Questions