Deferred Events Issue

I’ve noticed that when I code with deferred events enabled, CharacterRemoving doesn’t fire when my player leaves the game. Only PlayerRemoving does. However they both fire when immediate events are enabled. This is introducing some issues to my game because I know that immediate events are always enabled on online mode. I don’t know which one I should code with.

local PLAYERS = game:GetService("Players")

PLAYERS.PlayerRemoving:connect(function(player)
	print("Player removing") --prints all the time
	player.CharacterRemoving:connect(function(character) 
		print("Character removing") --only prints when immediate events are on
		character.AncestryChanged:connect(function()
			if character.Parent == nil then
				print("Character parent is nil") --only prints when immediate events are on
			end
		end)
	end)
end)
1 Like

What are “Deferred Events” and “Immediate Events”?

He’s referring to the new ways roblox will handle events, he’s trying to code using deferred but is having issues

1 Like

This might be a bug as CharacterRemoving does not fire when a player leaves (even if you use PlayerAdded instead of PlayerRemoving).

What happens is here CharacterRemoving fires after PlayerRemoving but before the deferred callback to the event handler for PlayerRemoving. Effectively, you miss the CharacterRemoving event because the handler runs later.

You can resolve this by checking if the character still exists when the player is being removed. If they don’t, the event has already fired.

Why is this behavior only with deferred events on?

Edit it also doesn’t print with this code:

local PLAYERS = game:GetService("Players")

PLAYERS.PlayerAdded:connect(function(player)
    print("Player added", player.Parent) --prints all the time
    player.CharacterRemoving:connect(function(character) 
        print("Character removing") --only prints when immediate events are on
        character.AncestryChanged:connect(function()
            if character.Parent == nil then
                print("Character parent is nil") --only prints when immediate events are on
            end
        end)
    end)
end)

The connection is already stated.

1 Like