Quick Help #1 – How to Remove an Item from an Array in GDScript

This is the first post in ‘quick help’ series. When I find a bug in my code and think it’s worth sharing, this series is where I’ll post it. Also everyone hates too long tutorials and examples. I’ll show you how to do things properly.

Prerequisites:

Godot v3.3

Problem:

Whenever I try to remove an item from an array, another item is removed.

var _item_array = ["knife", "bread"]

func _ready():
    remove_item("bread")

func remove_item(item):
    if _item_array.has(item):
        _item_array.remove(item)

This results in item_array with ‘bread’ even though that’s what you just removed.

Resolution:

Use erase -method instead of remove.

var _item_array = ["knife", "bread"]

func _ready():
    remove_item("bread")

func remove_item(item):
    if _item_array.has(item):
        _item_array.erase(item)

Now the correct item is removed.

Explanation:

If you take a look at remove -method documentation it states the following.

Removes an element from the array by index. If the index does not exist in the array, nothing happens. To remove an element by searching for its value, use erase() instead.

Here’s when it gets interesting. Instead of an index I passed in a string. First I would assume that nothing would happen since the documentation tells me ‘if the index does not exist in the array, nothing happens’. Well something happened!! Where is my knife for god sakes!? I have no clue at this point how the remove -method handles strings but apparently they somehow turn into a zero integers. Luckily the solution was pointed out in the last sentence from the documentation – the erase -method.

There you go. Happy coding!

One thought on “Quick Help #1 – How to Remove an Item from an Array in GDScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: