Custom object self destruction (OOP)

TL; DR
I want to make objects that can destroy themselves.

Long explanation
So I’ve made a custom class called Item which is the base class for custom items that players use. Some custom items (which I call Consumables) have to destroy themselves once there N attribute reaches 0.

I understand to destroy a custom object I need to remove all references to the object.

References to Item objects exist in a table in a Bag object which has its reference stored in the script PlayerItems. This is confusing so I drew this in paint

My first thought of how to achieve item self destruction was to call a bindable event from Item and listen for it in PlayerItems to search PlayerBags for the players bag then search the Bag for the Items name and remove it. However this seems like a convoluted way of achieving self destruction and causes issues if the player has more than one instance of an object in their bag. see below

To elaborate; N for the first apple could be 3 but if the second apple reaches 0 and calls a selfDestruct event than the first apple could be destroyed instead.

It seems the only plausible way of achieving my goal is to use some kind of unique identifier but I’m unsure how I could write a unique identifier for each object.

Couldnt you just set the object to nil, aka

function Item:Destroy()
 -- pre-cleanup
 self = nil
 -- post-cleanup
end
1 Like

You’re only setting the reference to itself to nil in the local scope self=nil; the object would still exist if other references to it are held.

My recommendation is for any destroyable objects to have a .Destroyed event which is fired upon calling :Destroy() before cleanup. Your bag would listen to this event for all items it holds and removes it from self.Slots.

1 Like

Setting self to nil would not do anything. The best solution would be to let the garbage collector do the destruction for you. You would only need to get rid of the references and it’s all good.

2 Likes