0 votes

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.isingroup("killzn"):

                            *** INSERT SOUND ACTIVATION HERE ***
            # Respawn
            score = 0; 
            update_score(); 
            #print(self.name + " has died.")
            respawn();  
            velocity = Vector2(0, 0); 
            continue; 
in Engine by (12 points)

1 Answer

+1 vote

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; 
    ...

https://docs.godotengine.org/en/stable/classes/class_audiostreamplayer2d.html

by (2,832 points)

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?

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.

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.