Hi, this is my first post in here. So first of all: It it awesome that a community like this exists and actually is active!
I am looking forward to becoming good at this and contributing my first game (probably next year ):
So here is my question:
I recently started with Unity. Here is my problem:
I have a game consisting of 3 scenes : Start Menu, Game, Game Over Menu.
Here is what I want to do:
When the Start Menu is opened, play Track01.
If the Game starts, play Track02.
If the Game over Menu starts, keep playing Track02.
When the Start Menu is entered, play Track01 again.
This is how I thought I would achieve it:
- Create one instance (Singleton) of a music player. Whenever a scene is loaded, check which scene currently is loaded, and resume/load track accordingly.
- Problem: When a new scene is loaded, I ask for the builtIndex, which has not been updated on the time of my query yet. Therefore, it still has the index of the previous scene
My Code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MusicPlayer : MonoBehaviour
{
private static MusicPlayer instance;
public static MusicPlayer Instance
{
get
{
return instance;
}
}
[SerializeField] AudioClip[] soundTracks;
private AudioSource audioSource;
// Use this for initialization
void Awake()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
private void Start()
{
audioSource = GetComponent<AudioSource>();
ChooseTrackToPlay();
}
public void ChooseTrackToPlay()
{
int index = SceneManager.GetActiveScene().buildIndex;
Debug.Log("current index: " + index);
if (index < soundTracks.Length)
{
if (audioSource.isPlaying)
{
Debug.Log("Detected Audio Source playing");
audioSource.Stop();
}
audioSource.clip = soundTracks[index];
audioSource.Play();
}
}
}
and
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Level : MonoBehaviour {
[SerializeField] float delayInSeconds = 3f;
public void LoadStartMenu()
{
SceneManager.LoadScene(0);
MusicPlayer.Instance.ChooseTrackToPlay();
}
public void LoadGame()
{
SceneManager.LoadScene(1);
GameSession.Instance.ResetGame();
Debug.Log("Loaded Scene: " + SceneManager.GetActiveScene().buildIndex);
MusicPlayer.Instance.ChooseTrackToPlay();
}
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad());
MusicPlayer.Instance.ChooseTrackToPlay();
}
private IEnumerator WaitAndLoad()
{
yield return new WaitForSeconds(delayInSeconds);
SceneManager.LoadScene(2);
}
public void QuitGame()
{
Application.Quit();
}
}