I’m trying to cap out a leaderstat so that if it exceeds the maximum value it resets the value to the maximum, and the opposite, making leaderstats reset back to 0 if they somehow go below 0.
I’m using this script but everytime it returns an error in line 3.
local players = game:GetService("Players")
local player = players.LocalPlayer
local leaderstats = player:WaitForChild("leaderstats")
local coins = leaderstats:WaitForChild("Coins")
local crystals = leaderstats:WaitForChild("Crystals")
local coinminimum = 0
local crystalminimum = 0
local crystalmax = 25000000000
while wait() do
if coins.Value < coinminimum then
coins.Value = coinminimum
end
if crystals.Value > crystalmax then
crystals.Value = crystalmax
elseif crystals.Value < crystalminimum then
crystals.Value = crystalminimum
end
end
Is there something i’m doing wrong? I’ve tried modifying how the script was done but it always returns the error “Workspace.CurrencyCapManager:3: attempt to index nil with ‘WaitForChild’”
I have looked for tutorials about this but found nothing so I had to do it myself and found nothing to help me.
That fixed it for me, thanks! The only issue is that it cannot reset the values back to 0 once they go below 0 which is one big issue the game constantly had where sometimes your currency would go straight to the smallest value possible. (I am fairly certain I’ve fixed that bug from ocurring, but negative values could still happen)
Use the math library’s min and max functions when calculating values.
local value1 = math.max(0, [[Calculate value here.]]) --Forces "value1" to contain a minimum value of 0.
local value2 = math.min(math.pi, [[Calculate value here.]]) --Forces "value2" to contain a maximum value of pi (3.14...).
There’s also the math.clamp() function that allows you to clamp a value between two other values.
local value = math.clamp([[Calculate value here.]], 0, math.pi) --Clamps the value of "value" between 0 and math.pi (3.14...).