I have sliders that the player can adjust and when they change it it gets saved in a PlayerPref so that when they get loaded into a different scene the setting gets saved and if they close the game it gets saved and everything is set up right, the Sliders aren't SetActive(false) or anything and it keeps giving me NullReferenceException for this line: s.source.volume = PlayerPrefs.GetFloat("SFX_Volume");
That line is in the ChangeVolume method and everything in the unity editor is set up right (to my knowledge at least). The code works when I do PlayerPrefs.DeleteAll() but not when I relaunch it afterwards without deleting playerprefs. Any ideas on why this could be happening?
(there are also no "isMusic" sounds in the editor yet) Thank you in advance!
This is the code:
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
public static AudioManager instance;
GameObject sliderSFX;
GameObject sliderMusic;
void Awake()
{
sliderSFX = GameObject.Find("SFX_Slider");
sliderMusic = GameObject.Find("Music_Slider");
if (PlayerPrefs.HasKey("SFX_Volume") != true){
PlayerPrefs.SetFloat("SFX_Volume", 1);
}
if (PlayerPrefs.HasKey("Music_Volume") != true){
PlayerPrefs.SetFloat("Music_Volume", 1);
}
sliderSFX.GetComponent<Slider>().value = PlayerPrefs.GetFloat("SFX_Volume");
sliderMusic.GetComponent<Slider>().value = PlayerPrefs.GetFloat("Music_Volume");
if (instance == null){
instance = this;
}
else{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
foreach(Sound s in sounds){
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
if (s.isMusic == true && s.isSFX == false){
s.source.volume = PlayerPrefs.GetFloat("Music_Volume");
}
if (s.isSFX == true && s.isMusic == false){
s.source.volume = PlayerPrefs.GetFloat("SFX_Volume");
}
s.source.pitch = s.pitch;
s.source.playOnAwake = s.playOnAwake;
s.source.loop = s.loop;
}
}
public void ChangeVolume()
{
var s_SFX_Slider = sliderSFX.GetComponent<Slider>().value;
var s_MusicSlider = sliderMusic.GetComponent<Slider>().value;
PlayerPrefs.SetFloat("SFX_Volume", s_SFX_Slider);
PlayerPrefs.SetFloat("Music_Volume", s_MusicSlider);
foreach(Sound s in sounds){
if (s.isMusic == true && s.isSFX == false){
s.source.volume = PlayerPrefs.GetFloat("Music_Volume");
}
else if (s.isSFX == true && s.isMusic == false){
s.source.volume = PlayerPrefs.GetFloat("SFX_Volume");
}
}
}
}
I checked if everything in the Editor was correct and it was and I researched about NullReferenceExceptions and none of the results I found worked for me