how to make the music last forver unity code example
Example 1: music that stays when you change scene unity
using UnityEngine;
public class MusicClass : MonoBehaviour {
private AudioSource _audioSource;
private void Awake()
{
DontDestroyOnLoad(transform.gameObject);
_audioSource = GetComponent<AudioSource>();
}
public void PlayMusic()
{
if (_audioSource.isPlaying) return;
_audioSource.Play();
}
public void StopMusic()
{
_audioSource.Stop();
}
}
Example 2: how to make the music last forver unity
GameObject.FindGameObjectWithTag("Music").GetComponent<MusicClass>().PlayMusic();
Example 3: how to make the music last forver unity
using UnityEngine; public class MusicClass : MonoBehaviour { private AudioSource _audioSource; private void Awake() { DontDestroyOnLoad(transform.gameObject); _audioSource = GetComponent<AudioSource>(); } public void PlayMusic() { if (_audioSource.isPlaying) return; _audioSource.Play(); } public void StopMusic() { _audioSource.Stop(); } }