The problem is that I can’t send a signal from my bullet to my player because the bullet is not instantiated yet.
However, I need to know when the bullet hits something, so I added an Area2D to the bullet and connected its signal to the bullet script.
Now I want the bullet scene to send a signal, which is received by three other scripts.
Is there a way to create or connect a signal at runtime when the bullet is spawned?
I’ve read the documentation about signals, but I couldn’t find anything that addresses this problem. I also searched around on DuckDuckGo, but the only solutions I found were very complex and relied on global scripts.
Yes. And you can await the bullet entering the scene succesfully as well using it’s ready signal, though I don’t think you need that.
In my pseudo code (typing on phone r.n.):
func spawn_bullet() -> void:
var bullet = YourPreloadedBulletSceneName.instantiate()
some_node.add_child(bullet)
# await bullet.ready
# don't think you need to await to connect the signal
bullet.your_hit_signal.connect(self.some_method)
bullet.your_hit_signal.connect(some_other_node.method)
Oh and you need to declare your_hit_signal too in the bullet script and call your_hit_signal.emit() from the method that receives a signal from its Area2D
Okay i have tried to conect it to my player but it dose not work, (bc i made a mistake)
and i get this error: Error at (9, 29): Cannot find member “bat_died” in base “Node2D”.
Her is my player code:
extends Node2D
@export var bat_scene: PackedScene
@onready var cpu_particles_2d: CPUParticles2D = $CPUParticles2D
var shooting = true
func _on_button_button_down() -> void:
if shooting == true:
cpu_particles_2d.emitting = true
var bullet = bat_scene.instantiate()
bullet.global_position = global_position
get_tree().current_scene.add_child(bullet)
shooting = false
func bat_died() -> void:
shooting = true
and her my bullet/bat:
extends RigidBody2D
signal bat_died
var shoot_power: int = 330
func _ready() -> void:
apply_central_impulse(Vector2(0.9, 0.1) * shoot_power)
bat_died.connect(Node2D.bat_died)
func _on_hurt_area_2d_area_shape_entered(_area_rid: RID, _area: Area2D, _area_shape_index: int, _local_shape_index: int) -> void:
bat_died.emit()