Topic was automatically imported from the old Question2Answer platform.
Asked By
Frvqz
Hey there!
I want to make a volume slider and it works quite well, except for one problem: When I return to the main menu, the volume control is set to the minimum (0) and I don’t know what the problem is…
Here is the code I use to adjust the volume control (only this line causes the problem):
When are you setting the value? Most likely not in a place that it stays updated. Use print("updated") just before it and switch between scenes to see if it outputs
beaverusiv | 2021-04-03 19:51
can you show us the _ready()-method of your main-menu-scene?
As whiteshampoo noted, the volume returned by get_bus_volume_db() is in decibels, which is not linear. If you want to control the volume with a slider, you should convert the decibels to linear values, using db2linear and linear2db. db2linear will return a value from 0 to 1, so you can multiply by 100 to get a range from 0 to 100 for you slider.
Oh wow, i didn’t know this functions exist! THANK YOU"!
I always calulcated this myself xD
whiteshampoo | 2021-04-05 10:34
i already using db2linear(). The volume slider is not the problem, it works fine. The problem is that I want to keep the slider at the volume level after restarting the scene. Because otherwise it resets itself to the normal value from the slider.
I made you an example of how it should work.
There is btw no need to set the values in global-variables
extends Control
onready var VolumeSound : HSlider = $VolumeSound
onready var VolumeMusic : HSlider = $VolumeMusic
# Set sliders when scene is loading
func _ready() -> void:
VolumeSound.value = get_linear_db("Sound") * VolumeSound.max_value
VolumeMusic.value = get_linear_db("Music") * VolumeMusic.max_value
# Some methods to make everything a bit nicer to read
func get_linear_db(bus_name : String) -> float:
assert(AudioServer.get_bus_index(bus_name) != -1, "Audiobus with the name " + bus_name + " does not exist.")
return db2linear(AudioServer.get_bus_volume_db(AudioServer.get_bus_index(bus_name)))
func set_linear_db(bus_name : String, linear_db : float) -> void:
assert(AudioServer.get_bus_index(bus_name) != -1, "Audiobus with the name " + bus_name + " does not exist.")
linear_db = clamp(linear_db, 0.0, 1.0)
AudioServer.set_bus_volume_db(AudioServer.get_bus_index(bus_name), linear2db(linear_db))
# Signals from sliders:
func _on_VolumeSound_value_changed(value: float) -> void:
set_linear_db("Sound", value / VolumeSound.max_value)
func _on_VolumeMusic_value_changed(value: float) -> void:
set_linear_db("Music", value / VolumeMusic.max_value)