Determine when model gets deleted that has script in it

I have a Tool that has a Script in it. That script requires a ModuleScript in ReplicatedStorage that creates a prototype for it. When the Tool gets deleted, the prototype should too.

So that’s what I’ve done. I connected AncestryChanged to the Tool, and if the 2nd argument (which I like to call parento) is nil, it’s been deleted.

Except it doesn’t work. When the script is deleted, the connection doesn’t fire, even though it’s in a different script. I’ve tried making the connection in a different coroutine, in an object method via metatables, it just doesn’t matter.

Likewise, ChildRemoved doesn’t work either.

It seems like it’s impossible, but maybe it isn’t. What do you guys think?

The design requirements for this implementation are:

  • the connection must be handled in the ModuleScript
  • no additional scripts may be added

Here is a place showcasing the behavior:

AncestryChanged Issues.rbxl (13.6 KB)

When the place is run, it is expected to see this in the output:

Part nil
Model nil

but only Part nil appears.

If you’re willing to use the CollectionService, perhaps I could offer you something. I don’t know how well this will fair for your use case though - I sort of just skimmed your post and replied (sorry).

What you could do is use the AddTag method of CollectionService. Tag everything except the tool with the new tag. Then, once your Tool gets removed, either above or below that code (depending on where the destroy code is - in the Tool or an external script), just write a quick loop to get items tagged the same way and remove them.

for _, object in pairs(CollectionService:GetTagged("group_name")) do
    object:Destroy()
end

I ended up using a BindableEvent in the module to call itself to create the connection, which worked.

It’s annoying that I have to use such a hack, but it works.

2 Likes