How to add a limit to NumberValue's minimum and maximum value

So I have these two buttons that increase and decrease the number on the screen above. The left button decreases, the right button increases.

However, I only want the NumberValue to go up or down to a certain amount, so it doesn’t exceed the limit. (The minimum being 0, and the maximum being 255.)

function OnClicked()

addremove = game.Workspace.ValuePart.SurfaceGui.Value.Value

game.Workspace.ValuePart.SurfaceGui.Value.Value = addremove + 1

game.Workspace.ValuePart.SurfaceGui.TextLabel.Text = addremove

end

script.Parent.ClickDetector.MouseClick:Connect(OnClicked)

This is the script for the “up” button. The down button is the same except it uses a - instead of a +.

Any suggestions on what to do?

5 Likes

You can use the math.clamp(x, min, max) function to clamp numbers.

local Gui = game.Workspace.ValuePart.SurfaceGui -- path to your SurfaceGui
function OnClicked()
    addremove = Gui.Value.Value
    Gui.Value.Value = math.clamp(addremove + 1, 0, 255)
    Gui.TextLabel.Text = addremove
end
script.Parent.ClickDetector.MouseClick:Connect(OnClicked)
5 Likes

Use math.clamp(x, min, max). If x < min, then min is returned. If x > max, then max is returned. Otherwise return x.

game.Workspace.ValuePart.SurfaceGui.Value.Value = math.clamp(addremove + 1, 0, 255)
3 Likes

robloxapp-20200527-2155155_Trim.wmv (463.1 KB)
Works great, but there’s a slight problem.

When the buttons are used, the value will add or subtract 2 numbers depending on the button you click. Is there any way to resolve this behavior?

I think you could use DoubleConstrainedValue too its deprecated

2 Likes

There’s a value called IntConstraintValue, which contains a Max, Min and current value, I prefer using this in stuff like health, level systems, etc.

I have noticed that you’re using a number value, I guess, use the value then:

1 Like

Try this:

local Gui = game.Workspace.ValuePart.SurfaceGui -- path to your SurfaceGui
function OnClicked()
    -- addremove = Gui.Value.Value << (removed this line, changed the one below)
    Gui.Value.Value = math.clamp(Gui.Value.Value + 1, 0, 255)
    Gui.TextLabel.Text = Gui.Value.Value
end
script.Parent.ClickDetector.MouseClick:Connect(OnClicked)

The math.clamp() function was specifically made to replace constrained value objects.

3 Likes