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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

How to play sound while changing scene?

Discussion in 'Scripting' started by Shayke, Aug 10, 2018.

  1. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
    I am trying to make a sound while i change scene but the sound get cut while doing it.
    I tryed this:
    Code (CSharp):
    1.     void Awake()
    2.     {
    3.          if (instance == null) { instance = this; } else { Destroy(gameObject); return; }
    4.            DontDestroyOnLoad(gameObject);
    5. }
    But it did'nt work.
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    I'm not sure what destroying a gameobject has to do with your question. All you do is set DontDestroyOnLoad on the GameObject with the audiosource, start playing it, then change the scene. You probably will want to set the audiosource to entirely 2D so it doesn't change in volume with a new audio listener in the new scene at a different location.

    I do this all the time to keep music playing while switching scenes, works fine.
     
    Last edited: Aug 10, 2018
  3. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
    It's for preventing multiple objects.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,599
    Just have a manager class that keeps track of if you have started a sound and either a) reuses it the next time, or b) destroys it and creates a fresh one.

    You can also explicitly destroy the GameObject after the sound is done.