How to activate AudioStreamPlayer2D within code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Jacob S

I am making a simple platform game, and trying to add sound effects. I downloaded some as .wav files, and have each attached to an AudioStreamPlayer2D. How would I activate these when I hit a certain object? Here is an example below:

elif object.is_in_group(“killzn”):

                            *** INSERT SOUND ACTIVATION HERE ***
			# Respawn
			score = 0; 
			update_score(); 
			#print(self.name + " has died.")
			respawn();  
			velocity = Vector2(0, 0); 
			continue;
:bust_in_silhouette: Reply From: timothybrentwood

Just get a reference to your AudioStreamPlayer2D then use the play() function.

onready var audio_player = $AudioStreamPlayer2D # whatever the path to your stream player is

...

elif object.is_in_group("killzn"):
    audio_player.play()
    # Respawn
    score = 0; 
    ...

It seems to work fine, except I get the error message “Attempt to call function ‘play’ in base ‘null instance’ on a null instance”. Any thoughts?

Jacob S | 2021-07-08 19:53

Either the path to your AudioStreamPlayer2D node is incorrect or you are queue_free()ing it and then calling play() on the player once it has been removed from memory.

timothybrentwood | 2021-07-08 21:56

Whenever you get an error like that (eg. invalid function call in base null instance or invalid index in base null instance, regardless of the node type, it means that the node that you referenced does not currently exist.

Snail0259 | 2021-07-09 06:58