C# script to controll sound volume level using UI Slider.

Simply, create UI Slider with minimal value 0 and maximum value 1. After that attach below script to it.

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

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

public class VolumeSlider : MonoBehaviour {
    [SerializeField] private Slider slider;

    void Start()
    {

        if (!PlayerPrefs.HasKey("SoundVolumeLevel"))
        {
            PlayerPrefs.SetFloat("SoundVolumeLevel", 1.0f);
        }
        else
        {
            slider.value = PlayerPrefs.GetFloat("SoundVolumeLevel");

            ChangeValue();
        }
    }

    public void ChangeValue()
    {
        AudioListener.volume = slider.value;
        PlayerPrefs.SetFloat("SoundVolumeLevel", slider.value);
    }
}

 

Unity C# UI Sound Level Controller
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504