Is there an option on the texture_button or something like that where you can specify a sound to be played on button-press. I have created a global sound_manager but for the button presses, I have to manually code it everywhere the script has a button_pressed signal. Or some kind of logic that when a button is pressed anywhere in the project, sound_manager plays a particular sound.
- \$\begingroup\$ Consider extending from TextureButton and allowing audio stream assignment as parameter. Here's an idea on reddit. Disclaimer - I have very little experience with Godot, so just giving you an idea. \$\endgroup\$eLTomis– eLTomis2020-07-15 13:46:59 +00:00Commented Jul 15, 2020 at 13:46
3 Answers
This can be done using an AutoLoad script that connects to the "pressed" signal of all buttons in the tree.
Create a UISoundPlayer scene which consists of a node with an AudioStreamPlayer attached, which is used to play the UI sounds.
Add that scene as an AutoLoad, and attach this script to the root node:
extends Node func _ready(): # when _ready is called, there might already be nodes in the tree, so connect all existing buttons connect_buttons(get_tree().root) get_tree().connect("node_added", self, "_on_SceneTree_node_added") func _on_SceneTree_node_added(node): if node is Button: connect_to_button(node) func _on_Button_pressed(): $ButtonSound.play() # recursively connect all buttons func connect_buttons(root): for child in root.get_children(): if child is BaseButton: connect_to_button(child) connect_buttons(child) func connect_to_button(button): button.connect("pressed", self, "_on_Button_pressed") The code should be self-explanatory. It connects to all buttons on _ready and to newly added buttons.
Here is an example project: https://gofile.io/d/LTBvQf
Another solution can be to make a new Scene, add an empty button to it, add a script to it and connect the pressed signal to sound_manager inside the init function. Then use this scene for every button which should make a sound. And, if the, sound is made an export var it can be customized in the editor.
Just want to add to Jummit's answer above (which got me out a bind because I didn't plan ahead, assuming Buttons would have a built-in way to make a noise, thank you Jummit)...
Be sure to set your UISoundPlayer node to Pause Mode Process so that the sounds still play when the game is paused.