Alternate approach using GDScript's `match`

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.

9 Likes

I simplified it even more by using get():

func play_sfx(sfx_name: String):
	var stream = get(sfx_name)
	if stream == null:
		return
	
	var soundplayer = AudioStreamPlayer.new()
	soundplayer.stream = stream
	soundplayer.name = "SFX"
	add_child(soundplayer)
	soundplayer.play()
	
	await soundplayer.finished
	soundplayer.queue_free()
2 Likes

Privacy & Terms