How to remove a deleted Object from an Array?

Godot Version

4.6.2

Question

Set-Up: I have two classes

  • CollectableComponent which is every “coin” tutorial you’ve seen, nothing should be surprising here. Important to not is that this class, for reusability reasons, also handles what happens when a collectable gets collected. Including freeing itself.
  • VacuumCollectable which “sucks in” all CollectableComponent’s within range. I’ve included a screenshot of the classes code below since this is where my problems are arising

The Problem I’m running into is, since CollectableComponent handles freeing itself, how can I remove its reference in VacuumCollectable.collectables_in_range? I know Godot doesn’t support deleting objects while iterating through an array, but I have to do something otherwise I get a memory leak. Moreover, if possible I’d also prefer it if this can be handled inside of VacuumCollectable itself since I don’t want the 2 classes coupled like that.

If anyone could please help me out that would be greatly appreciated.

Turn off your physics process before you clear the data.

your area can already query what objects are overlapping, maybe you should use $Area.get_overlapping_areas() instead of managing your own collectables_in_range?

Collectable should send a signal right before it gets deleted, passing a reference to self as the signal argument. The object that holds the list should then receive this signal and remove the reference from the array.

You can also just use a scene tree group instead of maintaining a custom array.

I forgot about get_overlapping_areas(). that solution worked perfectly, thank you!