- Home /
Music Manager script. Do I want a singleton?
I have a script attached to an object with to play music in my game. The only problem I have is that the level in which the object spawns (level1) is returned to sometimes within the game and then there are two music objects playing at the same time.
I've read up a bit on Singletons, but I'm unsure if it would benefit me or how I would implement it in this instance. The script is below:
using UnityEngine;
using System.Collections;
public class MusicScript : MonoBehaviour {
private AudioSource mySource;
void Awake()
{
DontDestroyOnLoad(gameObject);
if (Application.loadedLevelName == "Start")
{
Destroy(gameObject);
}
}
// Use this for initialization
void Start ()
{
mySource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
if (MenuController.gamePaused)
{
mySource.Pause();
}
else if (!mySource.isPlaying)
{
mySource.Play();
}
}
}
Thanks.
i guess if you want the music to keep playing through the scene change do the singleton, otherwise i would just make new things play each time
I do want the music to continue playing throughout the level changes without restarting.
Answer by Jamora · Jan 15, 2014 at 08:45 PM
Instead of instantiating a MusicScript every time the user enters level1. I would make an otherwise empty scene (think of it as level0) which is loaded when entering the game and that scene first instantiates the MusicScript and then loads Level1. Now, even if the player returns to level1, there won't be another instance of MusicScript instantiated.
One potential problem is that you need to load level0 every time you want to test your sounds. This thread gives a few suggestions on this particular problem.
Thanks! That does make sense to create a "loading" scene that doesn't get replayed. And thanks for pointing me to the Editor help!
Answer by Hydrashok · Sep 21, 2017 at 04:42 AM
``` public class MusicPlayer : MonoBehaviour { static MusicPlayer instance = null;
private void Awake()
{
Debug.Log("Music Initialized " + GetInstanceID());
if (instance != null)
{
Destroy(gameObject);
print("Duplicate Music Killed");
}
else
{
instance = this;
GameObject.DontDestroyOnLoad(gameObject);
}
}
// Use this for initialization
void Start ()
{
Debug.Log("Music Initialized " + GetInstanceID());
}
// Update is called once per frame
void Update ()
{
}
}
```