Godot has a handy if/else shorthand for checking a single variable called match
(this is similar to a switch
statement in other languages). You can use this to simplify the play_sfx
function a little bit:
func play_sfx(sfx_name: String):
var stream = null
match sfx_name:
"hurt":
stream = hurt
"jump":
stream = jump
_:
print("Invalid sfx name")
return
var asp = AudioStreamPlayer.new()
asp.stream = stream
asp.name = "SFX"
add_child(asp)
asp.play()
await asp.finished
asp.queue_free()
As you can see, the match
statement checks the variable sfx_name
for various “matches”. The _:
at the bottom denotes a default case that will be executed when sfx_name
matches none of the previous cases.