Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Randomly selecting a sound and playing it regardless of SceneManager.LoadScene

Discussion in 'Audio & Video' started by Mislav, Apr 1, 2016.

  1. Mislav

    Mislav

    Joined:
    Apr 1, 2016
    Posts:
    3
    Hello Unity developers,

    I was hoping maybe you could shed some light on this.

    I'd like to have a game in which sounds loop through the entire time (I created a list of AudioClips and it selects one sound from the list randomly). However, I want the sound to continue playing even after the level is restarted (via SceneManager.LoadScene).

    I managed to create a list of AudioClips and randomly pick one sound and attach it to the AudioSource. But here I encounter a problem.

    When I don't call DontDestroyOnLoad within my C# script, the sound restarts itself after level has restarted. I have tried using DontDestroyOnLoad function, but that creates a new Audio Listener every time that the level restarts (which gives me 2 sounds playing at the same time). I even tried calling the function that plays the sounds from Start() instead of Awake(), but with no avail.

    How could I fix this?

    Here's my code (attached to the MainCamera):
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class MainCamera : MonoBehaviour
    6. {
    7.  
    8.     public AudioClip[] songs;
    9.  
    10.     void Awake()
    11.     {
    12.         PlayRandom();
    13.         DontDestroyOnLoad(this.gameObject); // creates new Audio Listener every time level restarts
    14.     }
    15.  
    16.     void PlayRandom()
    17.     {
    18.         if (!GetComponent<AudioSource>().isPlaying)
    19.         {
    20.             GetComponent<AudioSource>().clip = songs[Random.Range(0, songs.Length)];
    21.             GetComponent<AudioSource>().Play();
    22.         }
    23.     }
    24. }
    25.  
     
  2. michaelhartung

    michaelhartung

    Joined:
    Dec 19, 2013
    Posts:
    72
    You could use a SingleTon class in your script that's instantiated only once and doesn't get destroyed when you're switching between scenes. This live session training will give you an idea about this method:

    https://unity3d.com/learn/tutorials...ining-archive/persistence-data-saving-loading

    Another, simpler method would be to add a variable "isPlaying" that you set when the sound starts playing that you can check before starting to play the sound.