How to save/load UI slider value

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
User avatar
Tony Li
Posts: 22062
Joined: Thu Jul 18, 2013 1:27 pm

How to save/load UI slider value

Post by Tony Li »

A Dialogue System user asked on YouTube:
how to save the value on a or more sliders and add the value to an gameobject or a audio volume slider and make unity remember the value?
I included a complete example scene at the bottom of this post.

The Dialogue System's save system is for saved games. You probably don't want to save the audio volume slider in each saved game. Instead, you should save the audio volume for the entire application. You can use PlayerPrefs to do this. Here's an example script:

SaveSliderToPlayerPrefs.cs

Code: Select all

using UnityEngine;

public class SaveSliderToPlayerPrefs : MonoBehaviour {

    public string playerPrefsKey = "SliderValue";

    private UnityEngine.UI.Slider m_slider;

    void Start()
    {
        m_slider = GetComponent<UnityEngine.UI.Slider>();
        if (m_slider != null)
        {
            if (PlayerPrefs.HasKey(playerPrefsKey))
            {
                m_slider.value = PlayerPrefs.GetFloat(playerPrefsKey);
            }
            m_slider.onValueChanged.AddListener(delegate { SaveSliderValue(); });
        }
    }
    void SaveSliderValue()
    {
        PlayerPrefs.SetFloat(playerPrefsKey, m_slider.value);
    }
}
If you want to save a slider's value with a saved game, write a Persistent Data component. They're easy to write, and the Dialogue System includes a starter template. You only need to copy the template and fill in where the comments instruct. Here's an example script:

PersistentSliderData.cs

Code: Select all

using UnityEngine;
using PixelCrushers.DialogueSystem;

public class PersistentSliderData : MonoBehaviour
{

    public string sliderVariableName = "Slider";

    public void OnRecordPersistentData()
    {
        var slider = GetComponent<UnityEngine.UI.Slider>();
        if (slider != null) DialogueLua.SetVariable(sliderVariableName, slider.value);
    }

    public void OnApplyPersistentData()
    {
        var slider = GetComponent<UnityEngine.UI.Slider>();
        if (slider != null) slider.value = DialogueLua.GetVariable(sliderVariableName).AsFloat;
    }

    public void OnEnable()
    {
        PersistentDataManager.RegisterPersistentData(this.gameObject);
    }

    public void OnDisable()
    {
        PersistentDataManager.RegisterPersistentData(this.gameObject);
    }

}
And here's an example scene that uses both scripts:

SaveLoadSliderExample_2017-04-09.unitypackage
Post Reply