How to delay loading the scene to play the sound

Viewed 96

How to delay loading the scene to play the sound? I'm trying to delay loading a scene so I can play the sound, but the sound stops in the middle or doesn't exist at all and the scene changes immediately Here is my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MeinMenu : MonoBehaviour
{

    static AudioSource audioScr;
    public void NewGame()
    {

        SoundManagerScript.PlaySound("clik");
        DontDestroyOnLoad(audioScr.gameObject);
        SceneManager.LoadScene("level 1");
        
    }
    public void LoadGame()
    {
        SceneManager.LoadScene(PlayerPrefs.GetInt("SavedScene"));
    }
    


}

1 Answers

Happens when the scene loads faster than the sound can finish playing.
When a scene loads by default, it destroys all objects on the previous scene, which includes your audio source.

One way is to mark your audio-source with DontDestroyOnLoad

// Somewhere after your audio source have loaded...
DontDestroyOnLoad(yourAudioSource.gameObject);

Note that this means you are likely to end up with a singular instance of Audio Source, as this audio source (or the game-object attached to it, to be exact) will only be destroyed manually via script.


The other is to just do a coroutine that does nothing until the audio source have finished playing:

    IEnumerator LoadSceneWithSoundCoroutine()
    {
        yourAudioSource.Play();

        // Denies loading while audio source is playing.
        while (yourAudioSource.isPlaying)
        {
            yield return null;
        }

        SceneManager.LoadScene("Your scene")
    }

    // ...

    StartCoroutine(LoadSceneWithSoundCoroutine());
Related