Godot Version
4.7
Question
So right now in my game I'd like to add sound effects whenever i press hover or select a UI node, the obvious solution is to simply make a class out of the base button or UI element class and use those as the foundation
but i was wondering if i can have an Auto-load that detect whenever a button is pressed or any UI element received a specific event and then play the sound itself, sort of, high-jacking the signal if that makes sense
Implement a signal handler in an autoload that connects to SceneTree’s node_added signal. There you can check the type of the added node and connect to any of its signals you want to handle.
have a autoload like this:
extends Node
var playback:AudioStreamPlaybackPolyphonic
const CLICK = preload("res://audio/click/click.wav")
const HOVER = preload("res://audio/click/hover.wav")
func _enter_tree() -> void:
var player = AudioStreamPlayer.new()
add_child(player)
var stream = AudioStreamPolyphonic.new()
stream.polyphony = 32
player.stream = stream
player.play()
playback = player.get_stream_playback()
get_tree().node_added.connect(_on_node_added)
func _on_node_added(node:Node) -> void:
if node is Button:
node.mouse_entered.connect(_play_hover)
node.pressed.connect(_play_pressed)
func _play_hover() -> void:
playback.play_stream(HOVER, 0, 0, randf_range(0.9, 1.1))
func _play_pressed() -> void:
playback.play_stream(CLICK, 0, 0, randf_range(0.9, 1.1))
exactly what i need thank you man!
also don’t i need to free all the nodes connected when the level changes?
i didn’t know there was a node_added method so that’s good to know
sorry for the late, i dont think you have to worry about freeing when changing scenes 