How can I get an auto-loaded scene to access a button node in a different scene?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By joustwilliams
:warning: Old Version Published before Godot 3 was released.

I have a StreamPlayer auto-loaded so that the background music starts playing as soon as the game is started. I want to be able to pause and resume the background music using a ‘pressed’ signal from a button in the game stage scene.

This is the script I have attached to my StreamPlayer:

extends StreamPlayer

func _ready():
	var btn_bgm = utils.get_main_node().get_node('hud/btn_bgm')
	if btn_bgm:
		print('got it')
		btn_bgm.connect('pressed', self, '_on_pressed')
	pass

func _on_pressed():
	if is_playing():
		set_paused(true)
	else:
		set_paused(false)

This is the get_main_node() function from the auto-loaded utils.gd script:

func get_main_node():
	var root_node = get_tree().get_root()
	return root_node.get_child(root_node.get_child_count() - 1)
	pass

When I run the game with the script as is, the StreamPlayer can’t find the ‘btn_bgm’ node, but when I changed it to:

extends StreamPlayer
    
    func _ready():
    	var btn_bgm = utils.get_main_node().get_node('hud')
    	if btn_bgm:
    		print('got it')
    		btn_bgm.connect('pressed', self, '_on_pressed')
    	pass

it can find the ‘hud’ (CanvasLayer), which is the parent of ‘btn_bgm’.

Any idea what the problem is? Am I going about this completely wrong? Any advice is appreciated!

Check the debugger, remote inspector to see the scene structure, maybe you are looking at the bad node (is hard to know here without knowing the scenes structure).

I would use a group instead to get the node I want, is easier to manage that way.

eons | 2017-02-02 18:01

Thx eons forgot about the profiler

leg0 | 2017-02-28 18:41

:bust_in_silhouette: Reply From: YeOldeDM

If all you need to do with your global streamplayer is pause-unpause it, you shouldn’t need any script on it at all. You can put the script on your button, or wherever it seems appropriate.

extends Button

func _ready():
    connect('pressed', self, '_on_pressed')

func _on_pressed():
    Music.set_pause(!Music.is_playing())

Just replace “Music” with whatever your StreamPlayer singleton is called.
Now, the only node your script needs to know the location of is the global one, which is easy to find :wink: