Hi, I’m creating a game with Godot 4.3 and I’m having a problem getting this script to work. When I press the button, it doesn’t work and displays the following error message: E 0:00:02:0723 musicbutton.gd:6 @ _ready(): Node not found: “AudioStreamPlayer2D” (relative to “/root/Node2D/MusicButton”).
<C++ Error> Method/function failed. Returning: nullptr
<C++ Source> scene/main/node.cpp:1792 @ get_node()
musicbutton.gd:6 @ _ready()
E 0:00:02:0723 musicbutton.gd:11 @ _ready(): AudioPlayer is not assigned! <C++ Source> core/variant/variant_utility.cpp:1092 @ push_error()
musicbutton.gd:11 @ _ready()
Here the scripts.
extends Button
@export var play_icon: Texture2D # Icône pour l’état “play” (notemusicalon.png)
@export var stop_icon: Texture2D # Icône pour l’état “stop” (notemusicaloff.png)
@onready var audio_player: AudioStreamPlayer2D = $AudioStreamPlayer2D
func _ready():
# Vérifier si audio_player est bien assigné
if audio_player == null:
push_error(“AudioPlayer n’est pas assigné !”)
return
# Initialiser l'icône du bouton au démarrage
update_button_icon()
# Connecter le signal "pressed" du bouton à la fonction _on_button_pressed
pressed.connect(_on_button_pressed)
# Connecter le signal "finished" de l'AudioStreamPlayer2D à la fonction _on_music_finished
audio_player.finished.connect(_on_music_finished)
func _on_button_pressed():
# Basculer entre play et stop
if audio_player.playing:
audio_player.stop()
else:
audio_player.play()
# Mettre à jour l'icône du bouton
update_button_icon()
func _on_music_finished():
# Si la musique est terminée et que le bouton est en mode “play”, relancer la musique
if icon == play_icon:
audio_player.play()
func update_button_icon():
# Changer l’icône du bouton en fonction de l’état de la musique
icon = play_icon if audio_player.playing else stop_icon