Last active
August 18, 2025 10:33
-
-
Save HungryProton/988dcf9da6daa55767eba318208f8824 to your computer and use it in GitHub Desktop.
Example script for adding sounds to every buttons in the whole project at runtime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
## Automatically plays a sound on button click and hover | |
## Make it an autoload to work. | |
# Sound files | |
# Replace the path with your own | |
const BUTTON_CLICK := preload("res://ui/sfx/click_soft.ogg") | |
const BUTTON_FOCUS := preload("res://ui/sfx/bong_001.ogg") | |
var _audio_player_button_click: AudioStreamPlayer | |
var _audio_player_button_focus: AudioStreamPlayer | |
func _enter_tree() -> void: | |
process_mode = Node.PROCESS_MODE_ALWAYS | |
_audio_player_button_click = _create_audio_player(BUTTON_CLICK) | |
_audio_player_button_focus = _create_audio_player(BUTTON_FOCUS) | |
get_tree().node_added.connect(_on_node_added) | |
func _create_audio_player(stream: AudioStream, volume := 0.0) -> AudioStreamPlayer: | |
var audio_player := AudioStreamPlayer.new() | |
audio_player.bus = &"Interface" # Replace with your own | |
audio_player.max_polyphony = 2 | |
audio_player.stream = stream | |
audio_player.volume_db = volume | |
add_child(audio_player) | |
return audio_player | |
func _on_node_added(node: Node) -> void: | |
if node is Button: | |
var button := node as Button | |
button.pressed.connect(_on_button_pressed) | |
button.focus_entered.connect(_on_control_focused) | |
func _on_control_focused() -> void: | |
_audio_player_button_focus.play() | |
func _on_button_pressed() -> void: | |
_audio_player_button_click.play() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment