0
\$\begingroup\$

For some reason, my slider and audio resets back to 0 when I stop and play the game after I changed the value. Here is the code, I can't spot anything wrong with it:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class MainAudio : MonoBehaviour {

public Slider slider;

void Awake()
{
    PlayerPrefs.Save ();
    GetComponent<AudioSource> ().volume = PlayerPrefs.GetFloat ("CurVol");
    if (slider)
    slider.value = GetComponent<AudioSource> ().volume;
}
public void VolumeControl(float volumeControl)
{
    GetComponent<AudioSource> ().volume = volumeControl;
    PlayerPrefs.SetFloat ("CurVol", GetComponent<AudioSource> ().volume);
    PlayerPrefs.Save ();
}
}
\$\endgroup\$
3
  • \$\begingroup\$ There is no statement that calls VolumeControl, you also only set the slider value at the beginning. Remember that AudioSource.volume is a float which is a value type. \$\endgroup\$ Jul 2 '15 at 9:25
  • \$\begingroup\$ I'm a beginner, So how do I fix it? \$\endgroup\$
    – user68099
    Jul 2 '15 at 10:23
  • \$\begingroup\$ The mistakes you made are basic object oriented learning gaps. Learn about reference types and value types and their differences. \$\endgroup\$ Jul 2 '15 at 10:25
0
\$\begingroup\$

You can use the Update method to update the current volume.

private void Update()
{
    VolumeControl(slider.value);
}

And use the OnApplicationQuit method to save your current volume to the PlayerPrefs. Receiving the saved volume from the PlayerPrefs in the Awake method can be done like in your code snippet, but without the PlayerPrefs.Save statement.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .