Home > Enterprise >  How do I keep my music going betwen scenes and not restart in unity
How do I keep my music going betwen scenes and not restart in unity

Time:07-22

My problem is that my music restarts when my player dies, I tried the "DontDesteroyOnLoad" so the music keeps playing betwen the scenes. But when my player dies and goes to the previous scene the first generated music dosent stop, it keeps going, and after the player goes to the previous scene it starts again . And it runs at the same time as the first generated one does. This is the code I have.

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

public class DontDestroyAudio : MonoBehaviour
{
  
    private void Awake()
    {
        
        DontDestroyOnLoad(transform.gameObject);
    }

    
}

CodePudding user response:

Create an emepty scene put all things that you want to manage during all the game cycles there. Like your music manager. Put the script with audio there and use DontDestroyOnLoad as you have written. At first, load that empty scene with your managers. And then load all your level scenes. This way you will only have one music manager for your entire game.

CodePudding user response:

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

public class AudioManager : MonoBehaviour
{
    public static AudioManager instance;
    [SerializeField]
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip audioClip;
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            Destroy(this.gameObject);
        }
    }
    public void PlayAudio()
    {
        audioSource.clip = audioClip;
        audioSource.loop = true;
        audioSource.Play();
    }
    public void StopAudio()
    {
        audioSource.Stop();
    }
}

Function Call :

AudioManager.instance.PlayAudio(); AudioManager.instance.StopAudio();

  • Related