Can I delete an Array object just by its position?

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

Me again with another question about Arrays; I have an Array with different objects and I would like to know if you can delete only one referring to its position in the Array, regardless of which object it is but simply if it occupies a specific position in the Array.

Something like:

var Array = [obj1, obj2, obj3]

If [expression]:
   
       Array[0].queue_free()

tks guys

:bust_in_silhouette: Reply From: Zylann

There are two things to do in your case:

  1. Remove the object from the array
  2. Delete the object itself (only if you want to, sometimes the array is just a temporary storage)

In the case of nodes, that’s how you do it:

var node = array[0]     # Get the node at 0
array.remove(0)         # Remove from the array
node.queue_free()       # Delete the node

Note that removing from the array will shift all following elements by one place, for example if there is an object at index 5 it will now be at index 4.

Your code helped me a lot;
I basically did it there, just changed the var node, not using

var node = array[0] but using the expression var node = array.front()

Anyway, your logic saved me. thank you very much

lucasfazzi | 2019-12-01 16:13

I also put an if condition to avoid the 0 size bug of the array;

so it went something like this:


var node = array.front()

if array.size() > 0:
    array.remove(0)
    node.queue_free()

lucasfazzi | 2019-12-02 17:35