Background Music Error!
Hi,
I am having trouble with my Background music. I assigned it to loop and not to delete on load but when you get back to the Main Menu it starts up again. I tried fixing it but I kept getting errors this is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class NotDeleteMusic : MonoBehaviour {
// Use this for initialization
void Start () {
// Identify your scene where you have to stop current running music and probably start new one
if (SceneManager.sceneLoaded += "MainMenu")
{
// Find the game object who is playing the audio and STOP audio clip.
GameObject.FindGameObjectWithTag("GameMusic").GetComponent<AudioSource>().Stop();
}
DontDestroyOnLoad(this);
}
// Update is called once per frame
void Update () {
}
}
Answer by HenryStrattonFW · Feb 04, 2017 at 11:20 PM
You're error is because your if statement is invalid. SceneManager.sceneLoaded is an event you subscribe to, not a condition, replacing that for a proper event subscription should give you the desired results.
using UnityEngine;
using UnityEngine.SceneManagement;
public class NotDeleteMusic : MonoBehaviour
{
void Start()
{
SceneManager.sceneLoaded += _SceneLoaded;
DontDestroyOnLoad(this);
}
private void _SceneLoaded(Scene lScene, LoadSceneMode lMode)
{
if (lScene.name.Equals("MainMenu"))
{
GameObject.FindGameObjectWithTag("GameMusic").GetComponent<AudioSource>().Stop();
}
}
}
The music still duplicates when you go to the $$anonymous$$ain $$anonymous$$enu
I've just a a thought. Is the object with this script on part of the $$anonymous$$ain$$anonymous$$enu scene? if so the reasons it will duplicate is that you mark the object as not to be destroyed, but if you then re-load the scene it came from a new instance of this object will be created.
This might explain why you have a duplicate, in which case you will need to upgrade your script to check if this music player already exists, and delete the duplicate on creation (essentially a self-enforcing singleton).
If not please zip up your project and email the zip or a dropbox link or something and I'll try to take a look at this after work to get to the bottom of it. henrystrattonfw@gmail.com
The music is gameobject on the $$anonymous$$ain$$anonymous$$enu scene. I don't understand what I am suppose to do sorry.
m_instanceexist doesn't exist in the current context
Apologies there was a missed keyword in that code where I was rushed.
private static m_InstanceExists = false;
should be
private static bool m_InstanceExists = false;
But you need to be able to spot this kind of error, always double check the code people give you as non of us are perfect :P debugging is one of the best skill you can have.