using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class AudioManager : MonoBehaviour
{
public GameObject gameAudio;
private AudioSource audioSource;
private string sceneName;
private bool currentScene = false;
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
// Start is called before the first frame update
void Start()
{
// Create a temporary reference to the current scene.
Scene currentScene = SceneManager.GetActiveScene();
// Retrieve the name of this scene.
sceneName = currentScene.name;
audioSource = gameAudio.GetComponent<AudioSource>();
var mainmenumusic = GameObject.Find("Main Menu Settings");
audioSource.volume = mainmenumusic.GetComponent<AudioSource>().volume;
}
// Update is called once per frame
void Update()
{
if (sceneName == "Game" && currentScene == false)
{
audioSource.Play();
currentScene = true;
}
else
{
if (sceneName != "Game")
{
audioSource.Stop();
currentScene = false;
}
}
}
//Called when Slider is moved
public void changeVolume(float sliderValue)
{
audioSource = gameAudio.GetComponent<AudioSource>();
audioSource.volume = sliderValue;
}
}
During Update, even if the Game scene has loaded (and only the Game scene is loaded) sceneNamesceneName is still set to "Main Menu":
if (sceneName == "Game" && currentScene == false)
sceneNamesceneName is never "Game."
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class BackToMainMenu : MonoBehaviour
{
public GameObject[] objsToDisable;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (Time.timeScale == 0)
{
DisableEnableUiTexts(true);
SceneManager.UnloadSceneAsync(0);
Cursor.visible = false;
Time.timeScale = 1;
}
else
{
Time.timeScale = 0;
MenuController.LoadSceneForSavedGame = false;
SceneManager.LoadScene(0, LoadSceneMode.Additive);
SceneManager.sceneLoaded += SceneManager_sceneLoaded;
Cursor.visible = true;
}
}
}
private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
{
DisableEnableUiTexts(false);
}
private void DisableEnableUiTexts(bool enabled)
{
foreach (GameObject go in objsToDisable)
{
if (go.name == "Cameras")
{
foreach(Transform child in go.transform)
{
if(child.name == "Main Camera")
{
if (enabled == false)
{
child.GetComponent<Camera>().enabled = false;
}
else
{
child.GetComponent<Camera>().enabled = true;
}
}
}
}
else
{
go.SetActive(enabled);
}
}
}
}
```