Volume Slider problem

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ManuelArtz

So I have a scene for the Options (separate from the Main Menu) . I’ve put 2 HSliders and I’ve made them work. My only issue is that after I go back to my Menu scene, the sliders reset to their original position (the volume remains the same though). How could I fix that?

:bust_in_silhouette: Reply From: jgodfrey

You’ll want to save the current values of the sliders (likely in a singleton for simplicity) and then reassign the saved values when you reload the Menu scene.

So, from a high-level:

  • Create a singleton to store the slider values in (and, probably assign them some reasonable default values)
  • When you load your menu scene, set the sliders to the values stored in the singleton
  • When the sliders are interactively changed, update the stored values in the singleton

Hey, I’ve tried doing that but it was confusing (to be honest, I am a beginner). Could you explain a bit furthermore?

ManuelArtz | 2022-03-26 05:43

Here’s a little more detail on the above outline…

Create a singleton to store the slider values. This will allow the values to live through scene changes. To do that, create a new script (say, Globals.gd) with your variables in it. For example:

extends Node
var volume1 = 50 # set a reasonable default value
var volume2 = 50 # set a reasonable default value

Now, set the script to be an autoloaded singleton via the Project | Project Settings | AutoLoad tab (select the new script and add it to the list).

With that, you can access the variables it contains from anywhere in your project simply by referencing the script and the variable. So, this, for example:

Globals.volume1 = 55 # change the global value to 55 

So, you now have the ability to both read from and write to the variables in that script from where you need - and the values will not be impacted by a scene change.

Now, you just need to use them to solve your problem.

So, when the Options scene loads, just set the value of the sliders to the values stored in the singleton. Something like this (depending on your scene tree layout and node names):

func _ready():
    $HSlider1.value = Globals.volume1
    $HSlider2.value = Globals.volume2

That’ll set the sliders to the current values when the scene loads

And, wherever you switch from the Options scene back to the MainMenu, you’ll want to update the globally stored values right before you do the switch (because the User may have interactively changed them).

So, that’d look something like:

Globals.volume1 = $HSlider1.value
Globals.volume2 = $HSlider2.value

Hope that helps.

jgodfrey | 2022-03-26 14:48

Hey! Sorry for taking so long to reply. I was busy with things (school and stuff). I wanted to tell you a huge thanks! It works perfectly!

ManuelArtz | 2022-04-13 05:30