Food script works in studio but not in game

23 Views Asked by At

I have been having this issue i don't know how to fix because the console does not show up any errors, so basically in studio it works normally taking away 10 of food every bit amount of time however in game it does not

local Datastoreservice = game:GetService("DataStoreService")
local datastore = Datastoreservice:GetDataStore("food")
print("Coucou toi !")
local debounce = false
game.Players.PlayerAdded:Connect(function(player)

    local Values = Instance.new("Folder")
    Values.Name = "Values"
    Values.Parent = player

    local food = Instance.new("NumberValue")
    food.Parent = Values
    food.Name = "Food"
    food.Value = 100

    userid = player.UserId

    local data
    local success, errormessage = pcall(function()
        data = datastore:GetAsync(userid)
    end)

    if success then
        if data then
            food.Value = data
        end
    else
        food.Value = 100
    end

    player.CharacterAdded:Connect(function()
        food.Value = 100
    end)
    while player.Character do
        food.Value = math.clamp(food.Value - 10, 0, 100)
        local hum = player.Character:WaitForChild("Humanoid")
        if food.Value == 0 then
            hum.Health -= 5
        else
            hum.Health += 5
        end
        wait(9)
    end
end)

game.Players.PlayerRemoving:Connect(function(player)
    local data = player.Values.Food.Value

    local success, errormessage = pcall(function()
        datastore:SetAsync(userid, data)
    end)

    if success then
        print("Player data saved.")
    else
        print("There was trouble.")
        warn(errormessage)
    end

end)

At line 31 (while player.Character do) before it was just a true and it worked fine until i ran into the error: script timeout: exhausted allowed execution time

1

There are 1 best solutions below

0
Tsering On

Move the loop inside the CharacterAdded event and instead of checking Player.Character, you can check if the player’s health is greater than 0. The loop terminates when the player dies in the game and will start again when they respawn.