I’m trying to connect a function to OnClientEvent. The problem is that each time the event is fired, a new thread is created. I have a while loop in the function connected to the event, and I don’t want it to create another loop every time the OnClientEvent is fired. Any help is appreciated.
playerZone.OnClientEvent:Connect(function(button,inZone)
while true do
if not inZone then return end
AddStat(button,1)
end
end)
function AddStat(stat,amount)
local Stat = StatsFolder:FindFirstChild(stat)
if not Stat then warn(Stat,"stat doesn't exist. Try renaming the part") return end
local StatGui = PlayerGui:FindFirstChild(stat)
Stat.Value += amount
StatGui.Text = Stat.Value
print("Stat added")
task.wait(0.5)
return Stat.Value
end
The while loop is the issue yes. It will continue indefinitely regardless of whether the event is fired again or not. To fix this, we can reset the loop each time the event is triggered by doing the following, let me know if this works:
local Processing = false
playerZone.OnClientEvent:Connect(function(button, inZone)
Processing = inZone
while Processing do
AddStat(button, 1)
end
end)
function AddStat(stat, amount)
local Stat = StatsFolder:FindFirstChild(stat)
if not Stat then
warn(Stat, "stat doesn't exist. Try renaming the part")
return
end
local StatGui = PlayerGui:FindFirstChild(stat)
Stat.Value += amount
StatGui.Text = Stat.Value
print("Stat added")
task.wait(0.5)
return Stat.Value
end