TransWikia.com

Add a sound to all the buttons in a project

Game Development Asked by Hamza Memon on November 2, 2021

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.

3 Answers

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.

Answered by idle_talent on November 2, 2021

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.

Answered by Hamza Memon on November 2, 2021

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

Answered by Jummit on November 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP