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

Subtracting from in variables only subtracts one, How do I fix this?

Asked by 3 years ago

So, Im making a part that when I click it it subtracts one from a variable. The click detector should work until it hits 0, and I get no errors on this part and it works fine besides for when I click it to subtract.

local clickdetector = game.Workspace["Forest Cavern"].PuzzleOne.ClickDetector

local bricklife = 10

if bricklife > 0 then
    clickdetector.MouseClick:Connect(function()
        local bricklife = bricklife - 1
        print(bricklife)
    end)
end

Heres the code I have written. What happens is, the bricklife starts as ten, then I click it and the bricklife prints 9 in the output, but when I click it again it prints 9 again, and doesnt go down. I clicked it 20 times and it still printed nine, showing its not just something wrong with the print statement. How do I make it so it continually subtracts?

2 answers

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

Okay, so you are creating a new variable every time, so here's how to fix this:

local clickdetector = game.Workspace["Forest Cavern"].PuzzleOne.ClickDetector

local bricklife = 10

if bricklife >= 0 then
    clickdetector.MouseClick:Connect(function()
        bricklife = bricklife - 1
        print(bricklife)
    end)
end

This should do it! Hope it helps!

0
Ok, The first part is solved, but now if bricklife is 0 or lower it doesnt stop pokemine1o9 44 — 3y
0
ok, so here is the second part of the fix alexfinger21 341 — 3y
Ad
Log in to vote
2
Answered by 3 years ago

The above answer fixed one problem, the other issue is that you have lines 5 and 6 mixed up.

local bricklife = 10

clickdetector.MouseClick:Connect(function()
    if bricklife > 0 then
        --code
    end
end)
0
Oh, Ok thank you! that makes a lot more sense. pokemine1o9 44 — 3y
0
I'll upvote alexfinger21 341 — 3y
0
Team effort alexfinger21 341 — 3y

Answer this question