How do I check that a part was :Destroy()'ed?. Just checking if the part’s Parent is nil doesn’t work because it would also include parts which were parented to nil directly via script.
I could possibly do a check by parenting the part to Lighting (or somewhere else that the player can’t see) and checking if it gets forcefully parented back to nil, but I was hoping that there would be a better way.
If you’re curious, I’m writing a module that generates and maintains list of parts with certain tag(s) (for tag-based ignore lists and whitelists, for example), and I’m wary of cases where parts are recycled.
Okay, it turns out :GetInstanceAddedSignal() fires whenever the part is either is parented to nil or is :Destroy()'ed anyway, so it turns out this isn’t necessary. Huh.
local function Destroyed(x)
if x.Parent then return false end
local _, result = pcall(function() x.Parent = x end)
return result:match("locked") and true or false
end
local x = Instance.new("Part")
print(Destroyed(x)) -- false
x:Destroy()
print(Destroyed(x)) -- true
You can always also just return the boolean of the pcall; I’m not aware of any other errors interrupting reparenting (besides RobloxLocked but that’s evadable on its own).
Another solution is to give it a special tag with CollectionService before being destroyed, and then check if they still have that tag. When a part is destroyed, all its tags are removed. This is also the way to implement a “Destroyed” event, rather than continuously checking if you can still set its parent.
If the part is parented to ReplicatedStorage, then that code wouldn’t work.
If you instead check that it’s a descendant of game (or that its parent is nil), it still wouldn’t work. You can parent things directly to nil and still reparent them back to workspace afterwards, but when you :Destroy() something, you can’t set its parent afterwards anymore.
So say that my part should only be parented to the workspace, and if it’s not, it’s destroyed in my game (bc I won’t ever parent the part to anything else other than workspace).
So would this code suffice for my scenario?
part.AncestryChanged:connect(function()
if (not part:IsDescendantOf(workspace)) then
--stuff
end
end)