I cant for the life of me figure out why my for loop sometimes doesn’t break when I want it to. I sometimes get multiple “kills” on the same process frame even though i have break as last line when criteria is met.
Here’s my code: (under _physic_process())
for i in get_slide_collision_count():
var collision = get_slide_collision(i)
if collision.get_collider() != null:
if collision.get_collider().is_in_group("enemy_group"):
if collision.get_collider().surrender == false:
var enemy_death = enemy_death_scene.instantiate()
enemy_death.position = collision.get_collider().position
add_sibling(enemy_death)
collision.get_collider().queue_free()
break
I also don’t see anything outside of this code block as to why this would occur. Please help! Thanks in advance!
surrender doesn’t seem to be the issue. I even took the if statement out of the code to test and same results occur. I will keep looking at my code. Thanks again!
Not sure how that happened in my paste, there were some indent formatting issues with the paste so might’ve deleted something by accident. actual code shows “collision.get_collider().queue_free()” - I will update my original post to reflect this. thanks!
After further trouble shooting, I think the problem is not this code…
I have multiple characters with this code on screen that attack enemies. Sometimes it seems 2 or more characters can attack the same enemy at the exact same time. I considered this initially but thought immediately calling queue_free() to the enemy would make this not an issue.
I will mark this post as solved soon, but if anyone has a good way to tackle the actual issue, let me know! thanks all
queue_free() is not instant. The deletion will happen at the end of the frame. It is simply tagged to be deleted. Thus, you could end up with it still around while the whole thing is called elsewhere.
It does reach the break statement. The problem was multiple characters with this script occasionally hitting the enemy at the exact same time, causing the code to fire multiple times in the same game frame.
My quick and dirty fix was just to move the enemy_death_scene and queue_free() code portions to a timer that times out very quickly, and cant be reset while it is counting down (if multiple hits occur quickly).
I will mark this as solved. Thanks all for your help once again!