Can someone help me with signals

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By javrocks

I would like to remove the arrow projectile from the scene when it hits the enemy script so in the enemy script i have a hurt box function and when the arrow enters, it emits a signal

extends KinematicBody2D
signal remove_arrow

func _on_Hurtbox_body_entered(body):
  emit_signal("remove_arrow")

Then in the projectile script its suppose to receive the signal and then remove itself

extends KinematicBody2D

onready var Enemy := get_tree().get_root().find_node("Enemy", true, false)

func _physics_process(delta):

      Enemy.connect("remove_arrow",self, "remove")

func remove():
  print ("arrow removed")
  queue_free()

It sometimes works and other times i get errors or it the game crashes

:bust_in_silhouette: Reply From: Wakatta

The _physics_process function is not where you want to call this code

Enemy.connect("remove_arrow",self, "remove")

as it gets called multiple times every physics step and you only need to make the call once so try the _enter_tree() or _ready() overrides

Also in the _on_Hurtbox_body_entered func the body param is most likely your arrow or a parent of and you can avoid complicating your code with the following changes

func _on_Hurtbox_body_entered(body):
    if "remove" in body:
        body.remove()

Or even

func _on_Hurtbox_body_entered(body):
    if "arrow" in body.name:
        body.queue_free()

Wakatta | 2021-09-25 03:18

I tried placing the code:

Enemy.connect("remove_arrow",self, "remove")

in the ready function and the enter tree function
But it gives me the (connect in base null instance) error

javrocks | 2021-09-25 03:36

Most likely due to the Enemy node not being part of the sceneTree during this call

onready var Enemy := get_tree().get_root().find_node("Enemy", true, false)

And you can resolve it like this

var Enemy

func ready():
    Enemy = get_tree().get_root().find_node("Enemy", true, false)
    Enemy.connect("remove_arrow",self, "remove")

Wakatta | 2021-09-25 03:47

ok its working now thanks

javrocks | 2021-09-25 18:06

Wait a sec i actually just realized that even though it is not giving me errors like before a the projectile is not being removed

so i tried all these functions:

    Predator.connect("remove_arrow",self, "remove")

 func remove():
   print ("arrow removed")
   queue_free()
 func _on_Hurtbox_body_entered(body):
   if "remove" in body:
    body.remove()


 func _on_Hurtbox_body_entered(body):
   if "remove" in body:
	body.remove()

None of them are removing the arrow from the scene
BTW The arrow is in a different scene to the Enemy

javrocks | 2021-09-25 22:50

Yeah that was my bad.

func _on_Hurtbox_body_entered(body):
   if body.has_method("remove"):
    body.remove()

Wakatta | 2021-09-28 23:23