Avoiding Earrape by creating Volume Sliders in Unity
Adding volume sliders to your unity projects is easy! By doing so, you also get access to many fun features! Timestamps: 0:00 Intro 0:29 Audio Source Volume 1:35 Audio Mixer 3:02 C# Script 4:12 Exposing Parameters 4:38 Putting it all together 5:06 Decibels and Volume 6:53 Default Value 7:44 PlayerPrefs 9:22 Volume Percentage 10:51 Subscribe :) Code: using UnityEngine; using UnityEngine.Audio; using UnityEngine.UI; using TMPro; public class VolumeSliderController : MonoBehaviour { public string VolumeType = "MasterVolume"; public AudioMixer Mixer; public Slider Slider; public TextMeshProUGUI VolumeText; public float Multiplier = 30f; [Range(0, 1)] public float DefaultSliderPercentage = 0.75f; private void Awake() { if (!PlayerPrefs.HasKey(VolumeType)) { PlayerPrefs.SetFloat(VolumeType, DefaultSliderPercentage); } Slider.onValueChanged.AddListener(SliderValueChanged); Slider.value = PlayerPrefs.GetFloat(VolumeType); } public void SliderValueChanged(float sliderValue) { Mixer.SetFloat(VolumeType, SliderToDecibel(sliderValue)); VolumeText.text = Mathf.Round(sliderValue * 100f) + "%"; PlayerPrefs.SetFloat(VolumeType, sliderValue); PlayerPrefs.Save(); } private float SliderToDecibel(float value) { return Mathf.Clamp(Mathf.Log10(value / DefaultSliderPercentage) * Multiplier, -80f, 20f); } }
Download
0 formatsNo download links available.