Home > Back-end >  This Script just loads the next scene instead of playing a sound, waiting, and then loading the next
This Script just loads the next scene instead of playing a sound, waiting, and then loading the next

Time:07-14

This Script just loads the next scene instead of playing a sound, waiting, and then loading the next scene. Someone please help me im not good at c#

public class Play_Sound : MonoBehaviour
{
    public AudioSource soundPlayer;

    void Update()
    {
        if (Input.anyKeyDown)
        {
            Play_This_Sound();
            SceneManager.LoadScene(2);
        }
    }

    public void Play_This_Sound()
    {
        soundPlayer.Play();
    }
}

CodePudding user response:

the Play () method will not freeze the program until the end of the sound. It will simply start playing the sound but then the script will continue to run. The most elegant solution is with coroutines. If you don't know what they are, search the net - they are a key topic in C #:

public AudioSource soundPlayer;

public void Update()
{
    if (Input.anyKeyDown)
    {
        if (!soundPlayer.isPlaying)
            StartCoroutine(PlayAndLoad());
    }
}

IEnumerator PlayAndLoad()
{
    //Play the sound
    soundPlayer.Play();
    //I wait for the soundPlayer to stop playing.
    yield return new WaitUntil(() => !soundPlayer.isPlaying);
    //Load the scene
    UnityEngine.SceneManagement.SceneManager.LoadScene(2);
}

if you think my answer helped you, you can mark it as accepted. I would very much appreciate it :)

  • Related