Question by
ImmenseMudkipz · Jul 26, 2017 at 02:01 PM ·
scenevariable
Why is my scene variable losing its value?
So I have a script that assigns the last scene that was loaded (if there was one) to a variable called "lastLoadedScene," which happens after a scene is loaded. All this is to determine when to switch what audioclip is playing in the background depending on the scene. But whenever I try to access the lastLoadedScene after it's already been assigned a value the last time a scene was loaded, it will return null.
public class MusicManager : MonoBehaviour {
public AudioClip[] levelMusicChangeArray;
private AudioClip thisLevelMusic, previousLevelMusic;
private AudioSource audioSource;
private Scene lastLoadedScene;
private void OnEnable () {
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable () {
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded (Scene scene, LoadSceneMode loadSceneMode) {
thisLevelMusic = levelMusicChangeArray [scene.buildIndex];
if (lastLoadedScene.IsValid () == true) { // This condition if never true no matter how many scenes are loaded, so previousLevelMusic never gets a value
previousLevelMusic = levelMusicChangeArray [lastLoadedScene.buildIndex];
}
if (thisLevelMusic && thisLevelMusic != previousLevelMusic) {
audioSource.clip = thisLevelMusic;
audioSource.loop = true;
audioSource.Play ();
}
lastLoadedScene = scene; // This is where I assign lastLoadedScene to the scene that was just loaded. However, whenever the game comes back to this method to load a level, lastLoadedScene doesn't have a value anymore
}
void Awake () {
DontDestroyOnLoad (gameObject);
}
void Start () {
audioSource = GetComponent<AudioSource> ();
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612130339im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
random loss of component variable value 2 Answers
Make a Scene variable 0 Answers
Reading from file (C#) + Information from scene to scene (C#) 0 Answers
How to update variable based on scene 0 Answers