get_collider() returns object which is freed one line of code later -> null instance. How to avoid that? (gd script)

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

There is a raycast colliding with another area2d, which is freed, because the unit was killed and removed by calling queue_free() apparently in the very time between line 3 and 4.

i would really like to use the colliding object in my code, so what can I do or is there a better way for doing this?

0:my code is the following:
1:func shoot():
2: if shoot_ray.is_colliding():
3: var collider = shoot_ray.get_collider()
4: if collider.get_groups().has(“vulnerable”):
5: collider.cause_damage(amount)

:bust_in_silhouette: Reply From: pgregory

I’d need to see more code to understand how that situation is arising, but on initial view, the question would be, why not queue_free() the collider after causing the damage?

I’m not the foremost expert in the inner workings of Godot, but I was under the impression that the queue_free() worked on a frame basis, so should only be actioned at the end of the frame, after all the scripts had completed, so I’m not sure how it’s possible to happen between lines of the code.

Perhaps another avenue to explore is to check Object.is_queued_for_deletion() on the collder before trying to call it. However, this feels like a hack, I’d want to understand how it’s possible that the collider can disappear between lines of code.