Why won't this run more than once?

Everything here is working properly, but when I click a second time, it wont execute.
I’m not quite sure what I’m missing here, help would be much appreciated! Thanks.

local speed = 4
local increment = 0
local direction = false -- false = left, true = right
local hm = 0

script.Parent.ClickDetector.MouseClick:Connect(function()
    if direction then
        increment = 2
    else
        increment = -2
    end

    for i = 1,50 do
        wait()
        script.Parent.Orientation = script.Parent.Orientation + Vector3.new(0,0,increment) * speed
        hm = i
    end

        if hm == 50 then
            direction = not direction
    end
end)
1 Like

Wo there!

Format your code properly

if condition then
    for i = 1,50 do
        if condition then
            -- code
        end
    end
end

instead of

if condition then
for i = 1,50 do
if condition then
-- code
        end
    end
end

It’s just much easier to read and understand, and fixing bugs will become a quicker process.

if direction then
  direction = false
else
  direction = true
end

Can be simplified to

direction = not direction
1 Like

i edited, is this better?

Now that you’ve indented it correctly, you should be able to find out why this only runs once. :slight_smile:

PS: the for-loop is still missing an indent level

1 Like

Close, but not quite yet. Put the for loop one indent more.

Your edit did help me find your issue, which is:

You are setting direction to true in the last if statement.
The for loop only runs in the part of the first if statement that runs only if direction is false.

I think it may be your intention to end the first if statement before it goes to the for loop:

if direction then
    increment = 2
else
    increment = -2
end

Make sure to remove the end second from the bottom, and put the for loop and the last if statement back one indent.

I was trying to see if there was a better way to do it, thank you for telling me this!

You’re also able to shorten the following

if direction then
  increment = 2
else
  increment = -2
end

to this

increment = direction and 2 or -2
1 Like

I got it fixed, added proper indentation, added a debounce, and made it more efficient!

Thanks, @woot3, @EmeraldSlash and @buildthomas!!

1 Like