0 votes

Hi,

I know there's probably an easier way to do this but I want to search through and array with dictionary entries, and if en entry is found that corresponds to the search, it will delete it. For example:

var enemies = []
enemies.append({enemy_name = "blob", enemy_position = Vector2(0, 0), enemy_health = 5})
enemies.append({enemy_name = "jelly", enemy_position = Vector2(2, 0), enemy_health = 3})
enemies.append({enemy_name = "spike", enemy_position = Vector2(5, 0), enemy_health = 4})
enemies.append({enemy_name = "claw", enemy_position = Vector2(5, 0), enemy_health = 5}) 

print("Enemies: ", enemies)
var health_to_delete = 5

for i in range(enemies.size()):
    if (health_to_delete == enemies[i].enemy_health):
        enemies.erase(enemies[i])
for i in range(enemies.size()):
    print(enemies[i].name)

The results should be: "jelly, spike"
Hope this makse sense. Also this doesn't work.
Thanks!

in Engine by (61 points)

1 Answer

+1 vote
Best answer

To avoid issues with invalid indices you'll have to go through the array in reverse order:

for i in range(enemies.size() - 1, -1, -1):
    if (health_to_delete == enemies[i].enemy_health):
        enemies.remove(i)
by (1,556 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.