This is a very dumbed down version of part of a turn based game, where I am trying to listen for players finishing their turns.
local buttonEvent = game:GetService("ReplicatedStorage"):WaitForChild("Click")
local testEvent = Instance.new("BindableEvent")
local flip = false
local function test2()
print("test 2")
task.wait(5)
testEvent:fire()
end
local function test1()
print("test 1")
local listener
listener = buttonEvent.OnServerEvent:Connect(function()
listener:Disconnect()
print("clicked")
testEvent:fire()
end)
end
testEvent.Event:Connect(function()
flip = not flip
if not flip then
test2()
else
test1()
end
end)
test1()
To reproduce, you will also need a button clientside to send the click remote event.
The issue arises when you spam click the button when test2() is currently running - though the listener in test1 should be disconnected, multiple click events are being processed (Though only after test2() finishes, for some reason.)
I feel like there is a very simple explanation that I am missing. Been pulling my hair out for hours, so any help is appreciated.
Huh, that’s good to know. I’ve used a similar setup of listener → disconnect() before without any issues (that I know of). To be clear - are you saying that I’m disconnecting the event before it’s defined, only for it to be defined after (and thus be still capable of firing?)
Sure. The code I posted is also the complete system (minus a button clientside to send the “button event”) so it should be fairly easy to reproduce on your end as well (if you haven’t already).
Notice how after test 2 has started running, I spam click. The listener should have been disconnected, yet it’s almost like the remotes from my spam click have been queued up and unleashed all at once after test2() finishes.
Update: For some reason, adding another event listener for the remote stops the problem completely. Which makes no sense? It’s a separate listener that should be completely irrelevant.
local buttonEvent = game:GetService("ReplicatedStorage"):WaitForChild("Click")
local testEvent = Instance.new("BindableEvent")
local flip = true
local function test2()
print("test 2")
task.wait(5)
testEvent:fire()
end
local function test1()
print("test 1")
local listener
listener = buttonEvent.OnServerEvent:Connect(function()
listener:Disconnect()
testEvent:fire()
end)
end
testEvent.Event:Connect(function()
flip = not flip
if flip then
test1()
else
test2()
end
end)
-- Adding this event listener stops the issue completely
buttonEvent.OnServerEvent:Connect(function()
end)
test1()