- Home /
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);
Try adding this in Start() of SoundManagerScript
DontDestroyOnLoad(gameObject);
Also can you tell where in the code the NullReferenceException happens?
Your answer

Follow this Question
Related Questions
literally can't code. 2 Answers
Anybody run into this 'Oculus.VR.dll could not be found?' 1 Answer
cant see my code on visual studio 2 Answers
Namespaces broke after updating 2 Answers
Debugging an Android device from Visual Studio 2019 2 Answers