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.
1 Answer
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.
-
\$\begingroup\$ It pop-up an error,error CS1061: Type
Slider' does not contain a definition forValue' and no extension methodValue' of typeSlider' could be found (are you missing a using directive or an assembly reference?) \$\endgroup\$– BobJun 30, 2015 at 5:00 -
\$\begingroup\$ Make sure you use UnityEngine.UI to interact with the UI through script. Check out the answer edit. \$\endgroup\$– JPtheK9Jun 30, 2015 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\$– jhockingJul 30, 2015 at 11:48
-
-
\$\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, 2015 at 17:05