'Roblox Leaderstats not updating/only updating once

Roblox Leaderstats aren't updating correctly. When told to update leaderstats, it sometimes doesn't update, and other times, it only updates once. Code is below:

game.ReplicatedStorage.sleep.OnServerEvent:Connect(function(plr)
    local en = plr.leaderstats.Energy
    en.Value += 1
    print(en.value)
    wait()
    local speed = 5.07 * ((en.Value / 10) + 1)
    plr.Character:WaitForChild("Humanoid").WalkSpeed = speed
    print(speed)
end)

On times it doesn't update, the print(en.value) says 1 while the leaderstat stays as 0. When leaderstat only updates once, the print only updates once as well. Edit: The leaderstat was defined/created in a previous script.



Solution 1:[1]

You are declaring the "en" variable right before you add one to the value in this function. This means that every time you run this code, you will reset the "en" variable. If you declare the variable outside of the scope of this function, it should get rid of your issues.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steven Abouchedid