0 votes

Hi!

I have a simple question to a difficult problem: How do i delete an item from a 2D array?

        if selectedHearts.size() > 0:
        for x in range(8):
            for y in range(10):
                if selectedHearts.has(hearts[x][y].get_node("Sprite")):
                    hearts[x][y].queue_free()

I need to remove hearts[x][y] in the loop here. how do i do it?

asked May 26 in Engine by Joakim Wennergren (19 points)

Not sure what you want to achieve: Removing any element (e.g. with hearts[x].remove(y)) would break your loop, since now there would only be 9 y elements left for the given x, not 10. Moreover, its not clear which elements should fill the gap: Should y be reduced (like in my line above), or x? Do you have an example project?

https://pastebin.com/0fUN2wSL
Here is all the code.

Everytime i queuefree() a node in hearts 2D array i get an error saying: "Attempt to call function 'getnode' in base 'previously freed instance' on a null instance." in my find_neighbour() function.

what im trying to do is to that element from the 2D array and later refill it.

2 Answers

0 votes

Looks like your array is keeping refereces to previously removed nodes, remember to remove from the array too if you are storing it on a variable.

Also, when removing things on arrays, you must do it on a reverse order, it can be achieved with:

for i in range(array_size, 0, -1)

And in some cases, you may need to do extra checks with is_instance_valid(your_node)

answered May 26 by eons (7,498 points)
0 votes

Thanks for the code! So you actually don't want to change the array dimensions (it should remain an 8x10 array all the time), but you only want to have empty elements in there! That's no problem, as long as you don't ask the script to search for a Sprite within an empty element (which leads to the error shown above). So all you have to do is replace

if selectedHearts.has(hearts[x][y].get_node("Sprite")):

with

# Is there a node in this element?
if is_instance_valid (hearts[x][y]):
   # If yes: Check the Sprite within the node
   if selectedHearts.has (hearts[x][y].get_node ("Sprite")):
answered May 26 by Thomas Karcher (592 points)
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 How to use this Q&A? before posting your first questions.