How to save/load UI slider value
Posted: Sun Apr 09, 2017 1:38 pm
A Dialogue System user asked on YouTube:
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
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
And here's an example scene that uses both scripts:
SaveLoadSliderExample_2017-04-09.unitypackage
I included a complete example scene at the bottom of this post.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?
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);
}
}
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);
}
}
SaveLoadSliderExample_2017-04-09.unitypackage