user18599658
user18599658

Reputation:

how to reproduce a sound effect while loading a scene

how to reproduce a sound effect while loading a scene? I would like to play a sound effect when moving to the next scene, but it does not play. I already tried with method DontDestroyOnLoad but it doesn't work and I get this error: NullReferenceException: Object reference not set to an instance of an object LevelLoader.LoadNextLevel () this is my script to manage sounds:

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

public class SoundManagerScript : MonoBehaviour
{
    public static AudioClip clikSound, shootSound;
    static AudioSource audioScr;
    // Start is called before the first frame update
    void Start()
    {
        
        clikSound = Resources.Load<AudioClip> ("clik");
        shootSound = Resources.Load<AudioClip>("shoot");
        audioScr = GetComponent<AudioSource> ();
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public static void PlaySound(string clip)
    {
        switch (clip)
        {
            case "clik":
                audioScr.PlayOneShot(clikSound);
                    break;

            case "shoot":
                audioScr.PlayOneShot(shootSound);
                break;
        }
    }
}

and this is the script for switching between scenes:

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

public class LevelLoader : MonoBehaviour
{
    public Animator transition;

    public float transitionTime = 1f;

    
    static AudioSource audioScr;
    public void LoadNextLevel()
    {
        DontDestroyOnLoad(audioScr.gameObject);
        SoundManagerScript.PlaySound("shoot");
        StartCoroutine(LoadLevel(SceneManager.GetActiveScene().buildIndex + 1));
        
        

    }
    
    
    IEnumerator LoadLevel(int LevelIndex)
    {


        
        transition.SetTrigger("Start");
        yield return new WaitForSeconds(transitionTime);
        SceneManager.LoadScene(LevelIndex);
        
        
        
        

    }
   


}

Upvotes: 1

Views: 69

Answers (1)

oistikbal
oistikbal

Reputation: 207

Becasuse you're required gameobjects are destroyed. AudioSource by itself not enough. Maybe your AudioListener destroyed?

To arrange those things. I recommend you to have multiple scenes. in example, Persistent scene, MenuScene, Level1 etc, and you can put your audios in Persistent scene.

You can have more than one scene via SceneManager.LoadScene("OtherSceneName", LoadSceneMode.Additive);. That's where multiple scenes gets it's power.

It may be hard but i recommend you to use Addressables for handling scenes and assets like audios.

Upvotes: 1

Related Questions