Incorrect Behavior of Destroying Event in Example Code

The Destroying event documentation in Roblox incorrectly describes the behaviour when an instance is destroyed with Instance:Destroy(). The issue is how the event handles yielding, mainly when a connected function yields. The documentation says that an instance should remain in place until the connected function yields, but in practice, this doesn’t happen.

Example from the Documentation:
“This sample demonstrates how an Instance being destroyed remains in place until the connected function yields.”

Copy code
local part = Instance.new("Part", workspace)

local function onPartDestroying()
    print("Before yielding:", part:GetFullName(), #part:GetChildren())
    task.wait()
    print("After yielding:", part:GetFullName(), #part:GetChildren())
end

part.Destroying:Connect(onPartDestroying)
part:Destroy()

In this example, the part should still exist in memory until the task.wait() yields, but that does not seem to be the case.

Reproduction Code:

local thing = function()
    local a = Instance.new("Part", game)

    local conn = a.Destroying:Connect(function()
        print(a.Parent, "before yield") -- Expected: "[game_name] before yield"
        task.wait()
        print(a.Parent, "after yield") -- Expected: "nil after yield"
    end)

    print(a.Parent, "before destroying") -- Expected: "[game_name] before destroying"
    a:Destroy()

    task.wait(1) -- This is the only yield outside the signal function
end

while true do
    -- The `thing()` function should work as expected according to the documentation
    thing()
end

Expected Behavior:
Before a:Destroy(), the Parent of the instance should print as [game_name].
After the Destroying event is fired but before yielding, the parent should still be [game_name].
After yielding, the Parent should be nil.

Actual Behavior:
Instead of staying in place until the connected function yields, the instance’s Parent appears to be set to nil even before yielding within the connected Destroying event. This contradicts the expected behaviour described in the documentation.

Steps to Reproduce:
Run the above code in Roblox Studio or play mode.
Look at the printed output during the destroy process.
See how the instance’s parent becomes nil before the expected yield in the Destroying event, which isn’t the described behaviour.

Page URL: https://create.roblox.com/docs/reference/engine/classes/Instance#Destroying

4 Likes

It looks like the documentation’s example works under Immediate signal behavior, but setting signal behavior to Deferred gets the results you’ve described. I’ll flag this for the team, thanks for bringing it to our attention!

3 Likes

The documentation has been updated, see here. We’ll also be adding documentation for deferred engine events in the near future, since it touches on a few other places like this. Let me know if you encounter any further issues!

1 Like