Unity play background music without restart the music when scene reloaded

Unity play background music without restart the music when scene reloaded

Step 1:  
Create an empty game object named like BackgroundMusic. and add a tag name like “BackgroudMusic”.
Step 2:
Add a AudioSource and attach a music on that.
Step 3: 

Create C# script named Background music or anything else . Attach the code to the gameObject

using UnityEngine;
using System.Collections;

public class BackgroundMusic : MonoBehaviour {
    
    private GameObject[] music;
    
    void Start(){
        music = GameObject.FindGameObjectsWithTag ("BackgroundMusic");
        if(music.Length > 0) {
             Destroy (music[1]);
        }
       
    }
    
    // Update is called once per frame
    void Awake () {
        DontDestroyOnLoad (transform.gameObject);
    }
}


 

Leave a Reply

Your email address will not be published. Required fields are marked *