Load the main volume and put its value on a NGUI slider

Hi. I will make screenshot and maximum things as I can do to make you understand.

I have a slider in my options, which controls the volume. When i click on “Apply”, the AudioListener.volume is stored in a XML file.

I go back to the menu, launch my options again.

Here is my load : my AudioListener.volume is at 0,171717172, but the slider’s initial value is set to 1. So the slider’s thumb is set to 1, but my volume to 0,1717172.

I wanted to put a temporary variable to set the AudioListener.volume at its value, and then, change the slider’s inital value to that’s temp var.

768-pb1.png

using UnityEngine;
using System.Collections;

public class VolumeSlider : MonoBehaviour
{
	public Transform vol;
	public static float val1;
	
	void Awake(){
		val1 = AudioListener.volume;
	}
	
	void Start(){
		UISlider levolume = vol.GetComponent<UISlider>() as UISlider;
		levolume.initialValue = val1;
		levolume.UpdateSlider();
	}
	
	void OnSliderChange (float val)
	{
		AudioListener.volume = val;
	}
}

nothing worked. I’m on this script since 6 PM, it’s 4 AM now …

I would like to change the slider’s initial value to the AudioListener.volume…

Please help.

For the current version of NGUI this is the answer to do what you want:

    private UISlider _slider;

	// Use this for initialization
	void Start ()
	{
	    _slider = gameObject.GetComponent<UISlider>();
	    _slider.sliderValue = AudioListener.volume;
	    _slider.onValueChange += OnValueChange;
	}

    void OnValueChange(float val)
    {
        AudioListener.volume = val;
        print(val);
    }

You should not get the AudioListener.volume only at Awake - it’s probably 1.0 by that time (Awake is called when the object is instantiated). The best alternative would be to set VolumeSlider.val1 and the slider position whenever the XML value is read and assigned to AudioListener.volume.

Don’t know if you’ve already given up or found the solution, for me it was moving the Value adaption from Start() to Awake() as I’ve read that the initial values defined in Unity are set in Start(). So I tend to think that these override the intended values.

I’m also using sliderValue instead of initialValue.

Here’s a snipped (in JS) of how I do it in my current project:

private var turns: UISlider;

function Awake()
{
turns = GameObject.Find(“Slider Turns”).GetComponent(UISlider);
turns.sliderValue = PlayerPrefs.GetFloat(“Max_Turns”);
}

Hope that it helps…

regards