Question by
emirkutluay · Apr 22, 2020 at 12:15 PM ·
audioaudiosourceaudioclipdontdestroyonload
How to make audio play at once.
My background music starts playing when you get into the main menu. But if I go to another scene and come back to the main menu the background music starts playing one more time. So they are playing on top of each other its like I hear the music from two different sources and they are not synced. My script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Animations;
public class MusicClass : MonoBehaviour
{
AudioSource bgSource;
void Start()
{
bgSource = GetComponent<AudioSource>();
bgSource.Stop();
bgSource.Play();
}
void Awake()
{
DontDestroyOnLoad(gameObject);
}
}
Comment
Best Answer
Answer by Hellium · Apr 22, 2020 at 12:31 PM
public class MusicClass : MonoBehaviour
{
private static MusicClass instance;
private AudioSource bgSource;
void Start()
{
bgSource = GetComponent<AudioSource>();
bgSource.Stop();
bgSource.Play();
}
void Awake()
{
if(instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else if(instance != this)
Destroy(gameObject);
}
}