Search code examples
luaroblox

Why is it when my player dies, the whole loop resets?


So I am working on a game. The code I provided is working properly, but for some reason when I die, the timer resets from the beginning. I have no idea what is causing this problem.

local countdownLabel = script.Parent
local intermissionUI = script.Parent.Parent.Parent

local function countdown()
    local counter = 20
    while counter > 0 do
        countdownLabel.Text = tostring(counter)
        counter = counter - 1
        wait(1)
    end
end

local function peaceDown()
    local counter = 30
    while counter > 0 do
        countdownLabel.Text = tostring(counter)
        counter = counter - 1
        wait(1)
    end
end

local function mainCountdown()
    local counter = 270
    while counter > 0 do
        countdownLabel.Text = tostring(counter)
        counter = counter - 1
        wait(1)
    end
end

local function hideUI()
    intermissionUI.ImageLabel.Visible = false 
    wait(10)
    intermissionUI.ImageLabel.Visible = true
end

while true do
    countdown()
    peaceDown()
    mainCountdown()
    hideUI()
end

Solution

  • Here is some information from the startergui documentation:

    When a Player.Character respawns, the contents of their PlayerGui are emptied. Children of the StarterGui are then copied along with their descendants into the PlayerGui.

    So every time you die a new script is generated replacing the one before. If this script is supposed to run per player you could create a script that uses Players.PlayerAdded to add a script to their player folder instead.

    If you're planning on having one global countdown you could have a script in serverstorage that updates a global variable in replicated storage that then is accessed by a local script that updates the Label