1
\$\begingroup\$

I have not use playerprefs before, I want to know how to keep the change of the audio when the player change it throughout the game.

\$\endgroup\$
1
\$\begingroup\$
using UnityEngine;
using UnityEngine.UI;

public class SliderSaver : MonoBehaviour {

    public Slider slider;

    void Awake ()
    {
        slider.Value = PlayerPrefs.GetFloat ("Slider value");
    }

    public void OnSliderChange (float newValue)
    {
        PlayerPrefs.SetFloat ("Slider value", newValue);
    }

}

This sets the slider's value in the beginning to the saved value then changes that saved value whenever the slider changes.

\$\endgroup\$
6
  • \$\begingroup\$ It pop-up an error,error CS1061: Type Slider' does not contain a definition for Value' and no extension method Value' of type Slider' could be found (are you missing a using directive or an assembly reference?) \$\endgroup\$
    – Bob
    Jun 30 '15 at 5:00
  • \$\begingroup\$ Make sure you use UnityEngine.UI to interact with the UI through script. Check out the answer edit. \$\endgroup\$
    – JPtheK9
    Jun 30 '15 at 5:30
  • 2
    \$\begingroup\$ Shouldn't you define a default value in GetFloat, for when you access it the first time before it has been set? \$\endgroup\$
    – jhocking
    Jul 30 '15 at 11:48
  • \$\begingroup\$ Yeah, if you'd like to. \$\endgroup\$
    – JPtheK9
    Jul 30 '15 at 17:04
  • \$\begingroup\$ This is heading in the right direction, but the code sample could be improved. There's no OnSliderChange MonoBehaviour call in Unity 5 (maybe you're thinking of NGUI?), so you may need to attach a listener to slider.onValueChanged to call this. The "Slider value" key should be a public string property (along with the default value as jhocking mentions above), so this class can be re-used to save multiple slider values, with the developer free to change their keys/defaults in the inspector. You should also look at clamping the value from PlayerPrefs to a valid range, since it's user-editable. \$\endgroup\$
    – DMGregory
    Jul 30 '15 at 17:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .