I’m making a city game, and there’d be a button where you could increase a intvalue. I made a script so it could change the intvalue, but prevent it from going into the negatives. However, when I tried to do it, it didn’t work. Thanks for helping:
local replicatedstorage = game:GetService("ReplicatedStorage")
local TaxEvent = replicatedstorage:WaitForChild("TaxEvent")
local Taxes = replicatedstorage:WaitForChild("Taxes")
local function changenum(player, num)
if player.Team == game.Teams.Leader then
if Taxes.Value >= 0 then
Taxes.Value = Taxes.Value + num
end
end
end
TaxEvent.OnServerEvent:Connect(changenum)
local function changenum(player, num)
if player.Team == game.Teams.Leader then
if (Taxes.Value + num) < 0 then
Taxes.Value = 0
else
Taxes.Value += num
end
end
end
This code will add/subtract num to/from Taxes, but won’t go under 0
You can do what @NeoGaming_RBLX did or you can do this (not sure if it works cause I haven’t tested it) if it’s the only script that adds the value of Taxes
local replicatedstorage = game:GetService("ReplicatedStorage")
local TaxEvent = replicatedstorage:WaitForChild("TaxEvent")
local Taxes = replicatedstorage:WaitForChild("Taxes")
local function changenum(player, num)
if player.Team == game.Teams.Leader then
Taxes.Value = math.clamp(Taxes.Value + num, 0, math.huge)
end
end
TaxEvent.OnServerEvent:Connect(changenum)
Fixed the code, I put a minus instead of a plus by mistake
local function changenum(player, num)
if player.Team == game.Teams.Leader then
if (Taxes.Value + num) < 0 then
Taxes.Value = 0
else
Taxes.Value += num
end
end
end
ok here, let’s say there’s a count variable that the value is 0, a minimum variable that’s 0, and a maximum variable that’s 20. Then we add 10 to count 5 times so it becomes 50, right? Well, math.clamp stops that from going to 50 and just limits it to the minimum and maximum variable so it can neither go below 0 or above 30.
local count = 0
local minimum = 0
local maximum = 30
for i = 1, 5 do
count = math.clamp(count + 10, minimum, maximum) -- doesn't add anymore after the third loop
print(count)
end