PlayerPref Not Loading Data

Code

Data to save / load volumes

    public void load()
    {
            SFXSlider = GameObject.Find("Sound Effect Slider").GetComponent<Slider>();
            MusicSlider = GameObject.Find("Music Slider").GetComponent<Slider>();

            MusicSlider.value = PlayerPrefs.GetFloat("MusicVolume");
            SFXSlider.value = PlayerPrefs.GetFloat("SFXVolume");
    }
    private void save()
    {
        PlayerPrefs.SetFloat("MusicVolume", MusicSlider.value);
        PlayerPrefs.SetFloat("SFXVolume", SFXSlider.value);
    }

Changing & Saving it

    public void ChangeMusicVolume()
    {
        MusicSource.volume = MusicSlider.value;
        save();
    }
    public void ChangeSFXVolume()
    {
        SoundEffectSource.volume = SFXSlider.value;
        save();
    }
SFXSlider = GameObject.Find("Sound Effect Slider").GetComponent<Slider>();
MusicSlider = GameObject.Find("Music Slider").GetComponent<Slider>();

These lines are because my Audio Manager ( This script ), is a public static gameobject and when transitioning between scenes and still wanting to change the volume I need to reassign the sliders

I’m calling it from another script ( GameManager )

    public void OpenSettingsPauseMenu()
    {
        PauseMenu_UI.SetActive(false);
        MainMenuSettings_UI.SetActive(true);
        audioManager.load();
    }

But it only gets the music slider right, And if I close the settings menu and then open it again, both the music and the sound effects are assigned, Why does it happen only on the second time, and I would be glad to know a way around it

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: Regarding GameObject.Find · UnityTipsRedux

More information: Why cant i find the other objects?

In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.
If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.

Once you address the findy-stuff above…

Here’s an example of simple persistent loading/saving values using PlayerPrefs:

Useful for a relatively small number of simple values.

If code that is supposed to work isn’t working, then it is…

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Alright, I’ve read everything, I managed to get the gameObject reference BUT…
I have another/same problem that I can’t figure out

    public void load()
    {
            SFXSlider = GameObject.FindWithTag("SoundEffectSlider").GetComponent<Slider>();
            MusicSlider = GameObject.FindWithTag("MusicSlider").GetComponent<Slider>();

            MusicSlider.value = PlayerPrefs.GetFloat("MusicVolume");
////////////////////////////////////////////////This////////////////////////////////////
            SFXSlider.value = PlayerPrefs.GetFloat("SFXVolume");
////////////////////////////////////////////////This////////////////////////////////////
    }

I have both references assigned correctly but the SFX slider stays on zero, I’m getting this error in the inspector
The Error

null reference at line 147
Full error

NullReferenceException: Object reference not set to an instance of an object
AudioManager.ChangeMusicVolume () (at Assets/AudioManager.cs:147)
UnityEngine.Events.InvokableCall.Invoke () (at <10871f9e312b442cb78b9b97db88fdcb>:0)
UnityEngine.Events.UnityEvent1[T0].Invoke (T0 arg0) (at <10871f9e312b442cb78b9b97db88fdcb>:0) UnityEngine.UI.Slider.Set (System.Single input, System.Boolean sendCallback) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Slider.cs:540) UnityEngine.UI.Slider.set_value (System.Single value) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Slider.cs:267) AudioManager.load () (at Assets/AudioManager.cs:160) GameManager.OpenSettingsPauseMenu () (at Assets/GameManager.cs:110) UnityEngine.Events.InvokableCall.Invoke () (at <10871f9e312b442cb78b9b97db88fdcb>:0) UnityEngine.Events.UnityEvent.Invoke () (at <10871f9e312b442cb78b9b97db88fdcb>:0) UnityEngine.UI.Button.Press () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70) UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114) UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57) UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction1[T1] functor) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:530)

btw, it’s only after switching scenes, When on the same scene the music slider works perfectly, but the SFX slider is not interactable. After switching I can interact with the SFX slider, But then both the music slider and SFX slider gives an error on value change, I’ve adjusted the code to the script you’ve attached above and I still don’t understand why this is happening.
Here is the full code just in case ( I marked the important parts )

Code

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class AudioManager : MonoBehaviour
{
    public static AudioManager instance;

    public AudioSource MusicSource;
    public AudioSource SoundEffectSource;

    [Header("Music")]
    [SerializeField] Slider MusicSlider;
    public AudioClip MainMenu;
    public AudioClip Levels_Looped;
    public AudioClip Boss_Start;
    public AudioClip Boss_Looped;

    [Header("Sound Effects")]
    [SerializeField] Slider SFXSlider;
    public AudioClip Shoot;
    public AudioClip Bomb;
    public AudioClip Explosion;
    public AudioClip Damaged;
    public AudioClip Death;
    public AudioClip Boss_Death;
    public AudioClip Bullet_Collide;
    public AudioClip Door_Move;
    public AudioClip Level_Completed;
    public AudioClip Game_Completed;
    public AudioClip[] GameOvers;
    public AudioClip MouseHover;
    public AudioClip MouseClick;
    public AudioClip Woosh;

    /// <summary>
    /// //////////////////////////////////////////
    /// </summary>
    private const float DefaultMusicVolumeLevel = 1.0f;
    private const float DefaultSFXVolumeLevel = 1.0f;

    private static string s_VolumeLevel = "VolumeLevel";
    private static string s_SFXLevel = "SFXLevel";

    public static float MusicVolumeLevel
    {
        get
        {
            return PlayerPrefs.GetFloat(s_VolumeLevel, DefaultMusicVolumeLevel);
        }
        set
        {
            PlayerPrefs.SetFloat(s_VolumeLevel, value);
        }
    }

    public static float SFXVolumeLevel
    {
        get
        {
            return PlayerPrefs.GetFloat(s_SFXLevel, DefaultSFXVolumeLevel);
        }
        set
        {
            PlayerPrefs.SetFloat(s_SFXLevel, value);
        }
    }

    private const bool DefaultTurboMode = true;
    private static string s_EnableTurboMode = "EnableTurboMode";
    public static bool EnableTurboMode
    {
        get
        {
            return PlayerPrefs.GetInt(s_EnableTurboMode, DefaultTurboMode ? 1 : 0) != 0;
        }
        set
        {
            PlayerPrefs.SetInt(s_EnableTurboMode, value ? 1 : 0);
        }
    }

    /// <summary>
    /// /////////////////////////////
    /// </summary>
    private bool _MusicStarted = false;

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);

        if(instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void PlayMusic(AudioClip clip)
    {
        MusicSource.clip = clip;
        MusicSource.Play();
    }

    public void PlaySoundEffect(AudioClip clip)
    {
        if(SoundEffectSource.gameObject.GetComponent<AudioSource>().clip == null)
        {
            SoundEffectSource.PlayOneShot(clip);

            StartCoroutine(ResetAudioSource(SoundEffectSource, clip.length));
        }
        else
        {
            AudioSource OtherAudioSource = SoundEffectSource.gameObject.AddComponent<AudioSource>();
            OtherAudioSource.PlayOneShot(clip);

            StartCoroutine(ResetAudioSource(OtherAudioSource, clip.length));
        }
    }
    IEnumerator ResetAudioSource(AudioSource Source, float time)
    {
        yield return new WaitForSeconds(time);
        if(Source != SoundEffectSource)
        {
            Destroy(Source);
        }
        else
        {
            Source.clip = null;
        }
    }

    public IEnumerator ChangeMusicToLooped(AudioClip Start_Clip, AudioClip Looped_clip, float time)
    {
        PlayMusic(Start_Clip);
        yield return new WaitForSeconds(time);
        PlayMusic(Looped_clip);
    }
/////////////////////////////////////////////////////////////////////////////////////////////
    public void ChangeMusicVolume()
    {
        MusicSource.volume = MusicSlider.value;
        save();
    }
    public void ChangeSFXVolume()
    {
        SoundEffectSource.volume = SFXSlider.value;
        save();
    }
    public void load()
    {
        MusicSlider = GameObject.FindWithTag("MusicSlider").GetComponent<Slider>();
        SFXSlider = GameObject.FindWithTag("SoundEffectSlider").GetComponent<Slider>();

        MusicSlider.value = MusicVolumeLevel;
        SFXSlider.value = SFXVolumeLevel;
    }
    private void save()
    {
        MusicVolumeLevel = MusicSlider.value;
        SFXVolumeLevel = SFXSlider.value;
    }
}
///////////////////////////////////////////////////////////////////////////

No, actually, this is the important part:

You should have fixed that first. Everything else is irrelevant, and nullrefs NEVER need a forum post.

This is also why we DON’T use GameObject.Find(): it causes nullrefs!!

Luckily, the answer for a nullref is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that
1 Like