I'm really new to using Unity and C#, I'll do my best to explain the situation and show relevant code.
So basically I am creating a Settings Menu in my game. Options I have are a fullscreen toggle, resolution dropdown, graphics dropdown and volume slider. All of these settings will maintain the selection on a scene change or the game being shutdown and run again, other than the volume slider.
In Unity, the volume slider will maintain it's selection. Just not in the game once it has been built. It will instead default back to middle of the slider.
Here is relevant code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using System.Linq;
using TMPro;
public class SettingsMenu : MonoBehaviour
{
public AudioMixer audioMixer;
public Slider volumeSlider;
private void Start()
{
volumeSlider.value = GetVolume();
}
public void SetVolume(float volume)
{
audioMixer.SetFloat("volume", volume);
}
public float GetVolume()
{
bool result = audioMixer.GetFloat("volume", out float value);
if (result == true)
{
return value;
}
else
{
return -40f;
}
}
Now as I have said, this all works fine within Unity itself, the issue arises when I build the game, changing scenes means that the slider just defaults.
Please let me know if you need any more information. Thanks in advance.
You are close, use PlayerPrefs to store the last value that was set.
Something like this:
public class MyClass
{
private const string VolumePreferenceKey = "preferred_volume";
private const string VolumeKey = "volume";
public AudioMixer Mixer;
public float GetVolume()
{
if (Mixer == null)
{
Debug.LogWarning("Mixer property is not set !");
return -1.0f;
}
if (Mixer.GetFloat(VolumeKey, out var volume))
{
return volume;
}
Debug.LogWarning("Mixer volume couldn't be retrieved !");
return -1.0f;
}
public void SetVolume(float volume)
{
if (Mixer == null)
{
Debug.LogWarning("Mixer property is not set!");
return;
}
if (!Mixer.SetFloat(VolumeKey, volume))
{
Debug.LogWarning("Mixer volume couldn't be set !");
return;
}
PlayerPrefs.SetFloat(VolumePreferenceKey, volume);
}
}
I wrote this quickly, adjust it to your needs.