Audio not playing when it is wanted but can normally play in the editor

Godot Version

4.3

Question

The audio won’t play
Code ↓


@export var speed: float = 1300
@export var damage: int = 20
var target_position: Vector2
var is_moving 
@onready var audio_player = $AudioStreamPlayer  

func _ready():
	audio_player.stop()  

func move_to(target: Vector2):
	target_position = target
	is_moving = true  

func _process(delta):
	if is_moving:
		var direction = (target_position - position).normalized()
		var distance = speed * delta
		if position.distance_to(target_position) > distance:
			position += direction * distance
		else:
			position = target_position
			is_moving = false  
			queue_free()  

func _on_area_2d_area_entered(area):
	print("Collision detected with:", area.name)  
	if area.is_in_group("Zombie"):
		print("Pea hit a zombie!")  
		var zombie = area.get_parent()  
		if zombie.has_method("take_damage"):  
			zombie.take_damage(damage)  
			print("Attempting to play audio...")  
			
			audio_player.play()  
			print("Audio should be playing now.")  
			
			_free_pea()  
		else:
			print("Error: Parent object lacks 'take_damage' method.")  # Debugging if method missing

func _free_pea():
	queue_free()  # Free the pea```

You are freeing the audio player immediately after playing, it doesn’t have a chance to play any audio

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.