Is there a script to prevent a users leaderstats value to going below 0?

A player in my game reported that their coins value went below 0 and into the negatives. Anyone know how to fix this?

1 Like

Do this
if player.leaderstats.Gold.Value <= 0 then

1 Like

Thats it? and where would I place this script?

either with your data store script or your shop, all you need to do is when the variable changes, detect if it’s below 0, if it is than set it to 0


	local leaderstats ="Folder", plr)
	leaderstats.Name = "leaderstats"
	local gold ="IntValue", leaderstats)
	gold.Name = "Gold"
		if gold.Value <= 0 then
			gold = 0

Place it below the leaderstats implementation.

You could use a for loop in pairs to cycle through the players and check if they have < 0 and then change it to zero.

In a serverscript.

It would be more efficient to check when gold is changed with the .Changed event.

local player = game.PlayersLocalPlayer

if player.leaderstats.leaderstatsname.Value < 0 then
player.leaderstats.leaderstatsname.Value = 0

This is a local script place in startergui sorry for the messy code typing on a phone

Or you convert this to a serverscript

Thanks, so this will prevent the value from going below 0?

I saw @fastkingyaya code. It will work. You can mark that topic as solved.

You can use math.clamp() on the number.

math.clamp(x, y, z):
x is the value you want to clamp
y is the minimum value x can be
z is the maximum value x can be

1 Like

To prevent it from going below zero,
rather than making it go under zero then back up to zero instantly, It would be best to handle this in the script where you subtract the Gold.

For Instance, if the player is hit, and he loses 10 Gold, but his current gold is 8, do

=== [In Server] ===
local losegold = 10 -- The amount of Gold to lose
if plr.Leaderstats.Gold.Value < losegold then -- If player gold (8) is less than losegold (10) then
	plr.Leaderstats.Gold.Value = 0 -- player gold = 0

Please don’t post unnecessary details as this post is solved, and the post would be bumped.

If i was to use this where would this be placed? A whole new script?

Something.Value = math.clamp(YourValue, MinValue, MaxValue)

Using math.clamp prevents the chosen value to go below a minimum and a maximum, it’s better than adding checks for them.
For example, you can do:

plr.Leaderstats.Gold.Value = math.clamp(value, 0, maximum) -- changing them to the proper values.

Wouldn’t :GetPropertyChangedSignal be more efficient than changed?

1 Like

Yep [30 charactersssssssssssssss]