Avoiding Earrape by creating Volume Sliders in Unity

Published: 16 July 2021
on channel: The True Duck
318
11

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);
}
}


Watch video Avoiding Earrape by creating Volume Sliders in Unity online without registration, duration hours minute second in high quality. This video was added by user The True Duck 16 July 2021, don't forget to share it with your friends and acquaintances, it has been viewed on our site 31 once and liked it 1 people.