Background music wont unpause

Godot Version

4.6.2

Question

I have this global music that extends to almost all of my scenes, except 2. One is just fine (the boss one) and the other will successfully pause the music, but when i leave the scene and go into one where it is supposed to resume it doesn’t.

class_name backgroundmusic

func _ready() -> void:
	if get_tree().current_scene.name == "boss room":
		stop()
	if get_tree().current_scene.name == "Main_Menu":
		stream_paused = true
	else:
		stream_paused = false

If your music playing node is an Autoload, the _ready() function will only call one time when the game loads. No matter how many times you change scenes, the music playing node will not reload / re-_ready() itself (at least not without help).

One solution I can think of is every time you change scenes, you send a signal to the music player to inform you are changing to X scene, and if that scene needs music then play it.

2 Likes

You can take a look at how I did this in my Sound Plugin, or just use it. In my plugin, it works like this:

@export var menu_music: AudioStream
@export var level_music: AudioStream

#In the menu
Music.play(menu_music)
#In the game
Music.play(level_music)

You just use get_tree().paused to pause and unpause the game, and the plugin switches between the two songs. I use it in all my games. You just have to make sure your menus are allowed to work when the game is paused.


Or to make what you have work, do this:

class_name BackgroundMusic


func _ready() -> void:
	set_music()


func set_music() -> void:
	if get_tree().current_scene.name == "boss room":
		stop()
	if get_tree().current_scene.name == "Main_Menu":
		stream_paused = true
	else:
		stream_paused = false

Then you can call BackgroundMusic.set_music() from your level’s _ready() function, or from your code that makes the switch.

Note that I changed backgroundmusic to BackgroundMusic to make your code easier to read, and to follow the GDScript Style Guide.

2 Likes