I have a script which let’s me use multiple sliders to control the values of my mixer,i have no idea to save and load these values when exiting the game`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class Options : MonoBehaviour
{
[SerializeField] private AudioMixer MainMixer;
[SerializeField] private AudioMixerGroup SFX;
[SerializeField] private AudioMixerGroup Music;
// Start is called before the first frame update
void Start()
{
Debug.Log(MainMixer.name);
Debug.Log(SFX.name);
Debug.Log(Music.name);
}
public void SetGeneral(float sliderValue)
{
MainMixer.SetFloat("Master", Mathf.Log10(sliderValue) * 20);
}
public void SetEffects(float sliderValue)
{
SFX.audioMixer.SetFloat("SFX", Mathf.Log10(sliderValue) * 20);
}
public void SetMusic(float sliderValue)
{
Music.audioMixer.SetFloat("Music", Mathf.Log10(sliderValue) * 20);
}
}
`
Does anybody know how i can save the values?
There are many ways to do this so ill point out the main ones and you can dive into the ones that suite you the most.
- You can use
OnApplicationQuit
to run logic before quitting the game (in your can should be saving the audio levels)
- You can save the audio level using
PlayerPrefs
, or you can create your own file (a .json
file for example) where you read/write the values , the location of that file should be given by Application.persistentDataPath
- On
Awake
, you can do a check to see if the file exists , if yes then just load the values and apply them to your mixer groups , if not then create one with some default values and apply it
If you care to use an existing solution, I have a package that solves this. It’s open source, no asset store and you can add it using Unity Package Manager by adding a git repository.
It’s a simple package that lets you create “config variables” that are automatically stored (in PlayerPrefs). Config variables can be listened to (so a change to it from your settings menu automatically propagates to the scene).
There’s a ready script called AudioConfigReader that lets you write a config varialbe to an audio mixer property.
There’s currently no “example” or documentation, but it’s pretty straightforward to use. Just create a new FloatConfigValue asset in your project, then add AudioConfigReader in your scene and associate it with the asset and your exposed mixer value.
If you care to try it (or even contribute to the repo), I will glady walk you through it.