Writing this before I move on, so I’m going to assume the next video has Ben writing this solution as has happened a couple times now! My solution was to create a private int named currentScene - I then added a new if statement to my level load script:
I’m using Unity 5, hence the kinda weird ‘OnLevelLoaded’ compared to his simpler ‘OnLevelWasLoaded’ method - with the code Ben wrote, ‘scene.buildIndex’ would just be the ‘level’ variable.
The idea here is that the music manager first checks to see if an audio track exists for the currently loaded scene. If it does, it then checks to see if the currently loaded scene’s index is the same as the int currentScene that I built earlier. The extra ‘currentScene = scene.buildIndex’ line is there to update the currentScene variable with the actual current scene. Effectively - if the music for this scene already started playing and nothing has interrupted it, the music will just keep on going.
I wasn’t able to make this exact code work even though I’m using Unity 5, but by keeping the code as OnLevelWasLoaded Method and just using your idea of a currentScene variable I was able to make it work thanks! Example code below:
It’s been months since I did it so I had to look it up. In case someone needs an alternative:
MusicControllerSingleton.cs (Line 32-52)
void OnEnable() {
//Tell our 'OnLevelFinishedLoading' function to start listening for a scene change as soon as this script is enabled.
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
void OnDisable() {
//Tell our 'OnLevelFinishedLoading' function to stop listening for a scene change as soon as this script is disabled. Remember to always unsubscribe every delegate you subscribe to!
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode) {
if (SceneMusicAssignments[scene.buildIndex] == null ||
SceneMusicAssignments[scene.buildIndex] == musicAudioSource.clip) {
return;
}
musicAudioSource.Stop();
musicAudioSource.clip = SceneMusicAssignments[scene.buildIndex];
musicAudioSource.loop = true;
musicAudioSource.Play();
}
I played around with this for a bit and this was the solution I got and It works beautifully. I am running Unity 4.6.9 for this project.
Oh, and there is an extra line added in to solve a problem from a later lesson that caused the music player to play at the preset volume instead of the volume set by the player preferences.
private int currentSong;
void OnLevelWasLoaded (int level) {
AudioClip thisLevelMusic = levelMusicChangeArray[level];
Debug.Log ("Playing clip: " + levelMusicChangeArray[level]);
if (thisLevelMusic && currentSong != level) { //If there's some music attached AND the music is not the same as what is already playing
audioSource.volume = PlayerPrefsManager.GetMasterVolume (); //This line added in lesson 142: UI Slidders For Options
audioSource.clip = thisLevelMusic;
audioSource.loop = true;
audioSource.Play ();
currentSong = level;
}
}