Repeat wait until loop not working

I made a repeat wait until loop that’s supposed to damage the target until the value is set to “stop”, but even after it’s set to stop, the damage continues.

Here’s my code:

local Event = script.Parent:WaitForChild("RemoteEvent")

Event.OnServerEvent:Connect(function(Player, Type, Mouse)
	if Type == "start" then
		repeat 
			wait(1.5)
			Mouse.Parent.Humanoid:TakeDamage(2)
		until Type == "stop"
	end
end)
4 Likes

It’s because you’re checking if the type equals to start, and since it is stop the code doesn’t work.

2 Likes

I’d suggest using coroutine to make your system, learn more about coroutines here:

1 Like

The problem with your code is that Type only gets evaluated once when the function gets called, and its value doesn’t get updated inside the loop.

local EventStart = Instance.new("BindableEvent")
local EventStop = Instance.new("BindableEvent")

EventStart.Event:Connect(function(Mouse)
	repeat 
		wait(1.5)
		Mouse.Parent.Humanoid:TakeDamage(2)
	until EventStop.Event:Wait()
end)

script.Parent.RemoteEvent.OnServerEvent:Connect(function(Player, Type, Mouse)
	if Type == "start" then
		EventStart:Fire(Mouse)
	elseif Type == "stop" then
		EventStop:Fire()
	end
end)

3 Likes

but it’s changing the value every time the event is fired, so is it not updating in the loop or is it not firing correctly?

where would i put this? inside the server script?

1 Like

no, because the loop cant detect when the type is changed, only the if statement, so use either coroutine of bindable events.

i’ve read the coroutine documentation and i dont see how i would implement it, so i think i’ll try bindable events. I just don’t know where to put the bindable events thing, in the server script?

1 Like

replace it with where your script is located…

Yes, Insert It in ServerScriptService

thank you!

character limit aaaa

2 Likes

ive been testing it and it only damages them when i initially press the key and then damages them again when i release the key, but nothing during holding

do you know why it only damages them when i press the key and release it, but no damage while i hold it?

Try this if this works:

local Event = script.Parent:WaitForChild("RemoteEvent")

Event.OnServerEvent:Connect(function(Player, Type, Mouse)
    if Type == "start" then
        local isRunning = true

        spawn(function()
            repeat
                wait(1.5)
                Mouse.Parent.Humanoid:TakeDamage(2)
            until not isRunning
        end)

        Event.OnServerEvent:Connect(function(Player, UpdatedType)
            if UpdatedType == "stop" then
                isRunning = false
            end
        end)
    end
end)

thank you so much! this worked while i was holding the keybind and when i just pressed it

1 Like

No need to thank me :wink:
Have a nice day m8

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.