How to make a volume control

I created a BGM and SE volume control, but it didn’t behave as expected, so I’d like to ask for help.
I had ChatGPT write the script, and I made a few minor adjustments myself.

I prepared an HSlider and the following script:

(BGM version)
extends HSlider

func _on_ready() → void:
var config := ConfigFile.new()
config.load(“user://settings.cfg”)

var bgm_v: float = config.get_value("audio", "bgm_volume", 1.0)

self.value = bgm_v

var bus := AudioServer.get_bus_index("BGM")
AudioServer.set_bus_volume_db(bus, linear_to_db(bgm_v))

func _on_value_changed(new_value: float) → void:
var bus := AudioServer.get_bus_index(“BGM”)
AudioServer.set_bus_volume_db(bus, linear_to_db(new_value))

var config := ConfigFile.new()
config.load("user://settings.cfg")
config.set_value("audio", "bgm_volume", new_value)
config.save("user://settings.cfg")

The script works, but when I start the game anew, the previous volume control settings are reflected. While this isn’t an issue if I continue from a saved game, how can I prevent this from happening when starting the game fresh?

Sorry, I resolved it myself.

1 Like