Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I disconnect this function in a server script?

I swear I was able to disconnect functions before but I seem to have forgotten. I have it so that when the player holds G, it fires a remote event which then activates the function, and when they release G it fires another remote event which is supposed to disconnect the function. I'm having a little trouble with that part. At first I tried this:

function bandaging(plr)
	local humanoid = plr.Character:WaitForChild("Humanoid")
	local wounds = humanoid.Wounds
	while wait() do
		if humanoid.Health > 0 then
			if wounds.Value > 0 then
				wounds.Value = wounds.Value - 1
			else
				return
			end
		else
			return
		end
	end
end

Bandaging.OnServerEvent:Connect(bandaging)

CancelBandaging.OnServerEvent:Disconnect(bandaging)

And then I got an error on the last line saying I couldn't use Disconnect I think. So then I tried changing it to lowercase and then got an error saying it was deprecated. My final attempt was this:

function bandaging(plr)
	local humanoid = plr.Character:WaitForChild("Humanoid")
	local wounds = humanoid.Wounds
	while wait() do
		if humanoid.Health > 0 then
			if wounds.Value > 0 then
				wounds.Value = wounds.Value - 1
			else
				return
			end
		else
			return
		end
	end
end

function cancelBandaging()
	bandaging:Disconnect()
end

Bandaging.OnServerEvent:Connect(bandaging)

CancelBandaging.OnServerEvent:Connect(cancelBandaging)

And that also didn't work. It said I was trying to index function with Disconnect. Any help is appreciated.

1 answer

:Connect method returns the connection of the event you just did. That way, you can do :Disconnect on it.

local connection = Bandaging.OnServerEvent:Connect(bandaging)

connection:Disconnect()

Please, accept the answer if is it helpful for you! I'm glad to help :)

This discussion is preserved as it was. New answers, comments, and votes are closed.