Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Why does it continue adding after the NumberValue reaches 1000?

Asked by
Nidoxs 190
8 years ago

So I have a NumberValue that is called Health and I want the max health to be 1000 and the min 0, if at any point it is under 1000 I want it to regenerate back to 1000 with a random interval of 1 to 50 but after 1000 it continues forever? Help! Here is what I had:

script.Parent.Value = 1000
while script.Parent.Value <= 1000 do
repeat 
script.Parent.Value = script.Parent.Value + math.random(1,50)
wait(math.random(1,5))  
until
script.Parent.Value == 1000
end

2 answers

Log in to vote
2
Answered by 8 years ago

Because you are seeing if it equals 1000. Since you are doing math.random(1,50) there's a chance that it could pass 1000. To fix that do script.Parent.Value >= 1000

Also you don't need the repeat until in there.

You can just do this

script.Parent.Value = 1000 --Not sure what's this for
while script.Parent.Value <= 1000 do
script.Parent.Value = script.Parent.Value + math.random(1,50)
wait(math.random(1,5))  
end

script.Parent.Value = 1000 --This will set it to 1,000 afterwards if you want it too.
0
I tried this but It still didn't work : script.Parent.Value = 1000 while script.Parent.Value <= 1000 do repeat script.Parent.Value = script.Parent.Value + 10 wait(math.random(1,2)) until script.Parent.Value == 1000 end Nidoxs 190 — 8y
0
I made an update on it. starwars 10 — 8y
Ad
Log in to vote
1
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
8 years ago

Never check if a number is exactly equal to something unless you know for certain that it will be. In this case, adding a random amount can very easily go over 1000 without reaching it.

The easiest way to make this work as expected is to connect the Changed event of the IntValue (I presume it is an Int and not a NumberValue) and have it set some 'regen' variable for use in an infinite loop:

local hp = script.Parent
local regen = false

hp.Changed:connect(function()
    regen = hp.Value < 1000
end)

while wait() do
    if regen then
        local healing = math.random(50)
        if healing > 1000 - hp.Value then --So we don't accidentally overheal.
            healing = 1000 - hp.Value
        end
        hp.Value = hp.Value + healing
        wait(math.random(5))
    end
end
0
Thanks for the help but I fixed it by using a humanoid in a brick I used it as a cap so It couldn't go over 1000, thanks though! Nidoxs 190 — 8y

Answer this question