Search Unity

Unity 4.6 New UI: Assign Slider OnValueChanged function via scripting

Discussion in 'Scripting' started by ssingh1, Nov 28, 2014.

  1. ssingh1

    ssingh1

    Joined:
    Dec 6, 2013
    Posts:
    2
    Can anyone please tell ,how to access camera's audioSource and select volume option through scripting. So that when slider is used, volume increases or decreases automatically. Any help would be great.
     
  2. Barachiel

    Barachiel

    Joined:
    Nov 25, 2012
    Posts:
    147
    I'm not sure if you're after an answer in Unityscript or C#, so I'll use Unityscript since that's what I've been writing in lately.

    So to start with, you'd want to place something like this above your Start function:

    Code (JavaScript):
    1. var volumeSlider : UnityEngine.UI.Slider;
    2. var audioSource : AudioSource;
    Then, inside the Start function, we'll grab a reference to both of these items. Since your question implies that the whole thing should be done with code, we can do something like this:

    Code (JavaScript):
    1. function Start ()
    2. {
    3.     audioSource = GameObject.Find("MainCamera").GetComponent(AudioSource);
    4.     volumeSlider = GameObject.Find("VolumeSlider").GetComponent(UnityEngine.UI.Slider);
    5. }
    In this case, the camera the AudioSource is attached to is named MainCamera and the Slider is named VolumeSlider. You can replace the names here with whatever you've called your objects, but the names need to match.

    Finally, we link the volume with the slider like so:

    Code (JavaScript):
    1. function Update ()
    2. {
    3.     audioSource.volume = volumeSlider.value;
    4. }
    The Slider has a default min/max value of 0.0 to 1.0. This corresponds to the AudioSource volume just fine so you shouldn't need to change the default values. Now if you hit play, using your mouse to adjust the slider will adjust the AudioSource volume. =)