assuming u want to disconnect or connect it based on a boolean u can do something like this
local state = false
local event = nil
game:GetService("RunService").Hearbeat:Connect(function()
if not state and not event then
event = part.Touched:Connect(function()
end)
elseif state then
pcall(function()
event:Disconnect()
event = nil
end
end
end)
local touchconnect
local newthread = function()
wait(1)
print("one")
wait(1)
touchconnect:Disconnect()
print("two")
wait(1)
print("three")
end
newthread()
touchconnect = (newthread)
I got an error and I was trying to test it, how would it work on a regular function? I wanna disable my whole entire function ( OnServerEvent ) so idk how to disable normal functions/threads. This test gave me an error (i am new to this disconnect thing) : ServerScriptService.Script:7: attempt to index function with ‘Disconnect’
When you start a function it doesn’t make a new thread. Luau is functional, so when you set touched connection to the function it sets the value of it to a function. It has to be a RBLXConnection to call disconnect on it.
If you want a function to stop mid way through you’d need checks after every yield (ex wait()). You can use Disconnect to stop a connection.
local func = coroutine.create(function() -- coroutines can create new threads which can be yielded whenever you want
-- code for the function
end)
local stopVal = Instance.new("BoolValue", player) -- bool values can hold true or false statements
stopVal.Name = "Stop"
stopVal.Value = false
stopVal:GetPropertyChangedSignal("Value"):Connect(function()
if stopVal.Value then
coroutine.yield(func) -- stop the function
func = nil
end
end)
coroutine.resume(func) -- call the function