Function stopping when player dies

I am making a checkpoint system. everything works up until the player dies.
When the player dies the function just stops, even the events

function obbyStart(plr, obby)
    if plr then  --  player exists
        if mapsFolder:FindFirstChild(obby.Name) then -- map exists
            --print("Obby Start")
            plr.PlayerGui.GameUI.GameUI.Visible = true
        end
    end
    
    local spawnCFrame = obby.Checkpoints.Start.CFrame
    local currentStageNumber = 0
    local checkPoints = obby.Checkpoints:GetChildren()
    
    plr.Character.PrimaryPart.Touched:Connect(function(touch)
        if string.find(touch.Name, "Checkpoint") then
            local stageNumber, _ =touch.Name:gsub("%D+", "") -- remove all letters
            stageNumber =  tonumber(stageNumber)
            
            if stageNumber == 0 or currentStageNumber < stageNumber then
                print(plr.Name.." touched "..touch.Name)
                
                currentStageNumber = stageNumber
                spawnCFrame = touch.CFrame
            end
        end
    end)
    
    plr.Character.Humanoid.Died:Connect(function()
        print(plr.Name.." Died")
        if spawnCFrame then
            wait(players.RespawnTime)
            repeat wait() until plr.Character.Humanoid.Health == 100 -- wait until character respwaned
            plr.Character:SetPrimaryPartCFrame(spawnCFrame)
        end
    end)
end
players.PlayerAdded:Connect(function(player)
    local inGame = false
    print("Player joined: "..player.Name)
    
    player.CharacterAdded:Wait()
    
    print("Character loaded: "..player.Name)
    
    local char = player.Character
    
    print(player.Name.." character added")
    local hrp = char:WaitForChild("HumanoidRootPart")

    hrp.Touched:Connect(function(touch)
        if has_value(mapStarts, touch) and not inGame then
            inGame = true

            local map = touch.Parent.Parent
            print(player.Name.." started "..map.Name)

            obbyStart(player, map)
        end
    end)
end)
1 Like

That happens because everytime a player’s character humanoid dies, the current player’s character is deleted and a new one is loaded, which means that this function:

plr.Character.PrimaryPart.Touched:Connect(function(touch)

will stop working, as you’re connecting it to the HumanoidRootPart of the character that gets deleted (since it gets deleted as the new one gets loaded).
So the only way to accomplish what you’re trying to do is connecting the function to each new character that gets loaded. Or, you can disable Players.CharacterAutoLoads and respawn the character manually.

2 Likes

Oh, that makes a lot of sense! I don’t understand how respawning manually would help, could you elaborate on that?

Manually respawning would help you get the character because you will know when the new character is made.

This also worked but I just changed it so that I teleported the player instead of killing