user14633516
user14633516

Reputation:

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

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);
    }

    
}

Upvotes: 0

Views: 722

Answers (2)

Prakyath
Prakyath

Reputation: 59

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();

Upvotes: 0

Milad Qasemi
Milad Qasemi

Reputation: 3059

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.

Upvotes: 1

Related Questions