Sound when button switch scene

491 Views Asked by At

What I am trying to do is when I press the button, it makes a sound and switch scene but it is delay 2s or 3s when i press the button and then it makes a sound so when i press a button it switches scene but doesn't make a sound ma code is:

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

public class mainManuControler : MonoBehaviour {
    
     public AudioSource src;
    
     public AudioClip srcOne;

     public void PlayGame() {

        src.clip = srcOne;

        src.Play();

        SceneManager.LoadScene("Game");
    }
}

How i can get rid of delay in audio.

1

There are 1 best solutions below

0
Armin On

It might be because you play the sound and immediately change scene. You can wait for the sound to finish playing then load that scene. See if this works:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
    
public class mainManuControler : MonoBehaviour
{

    public AudioSource src;
    public AudioClip srcOne;

    public void PlayGame()
    {
        src.PlayOneShot(srcOne);
        StartCoroutine(_PlayGame());
    }

    private IEnumerator _PlayGame()
    {
        yield return new WaitForSeconds(srcOne.length);
        SceneManager.LoadScene("Game");
    }
}