How to disconnect a function after the function plays

How would i disconnect a function after the function plays?

	local touch = character.HumanoidRootPart.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChild("Humanoid") and not hit.Parent:FindFirstChild("tag") then
			local EHumanoid = hit.Parent:FindFirstChild("Humanoid")
			EHumanoid:TakeDamage(10)
			local tag = Instance.new("StringValue")
			tag.Name = "tag"
            tag.Parent = hit.Parent
			Debris:AddItem(tag,1)
			
		end
	end)
		touch:Disconnect()

Did you tried to put touch:Disconnect() inside the Touched event?

1 Like

Yea, it says "Unknown global “touch”

Not sure if I quite understand what you’re trying to achieve, but maybe a debounce will work.

local debounce = false -- debounce variable
local touch = character.HumanoidRootPart.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") and not hit.Parent:FindFirstChild("tag") and debounce == false then
		local EHumanoid = hit.Parent:FindFirstChild("Humanoid")
		EHumanoid:TakeDamage(10)
		local tag = Instance.new("StringValue")
		tag.Name = "tag"
        tag.Parent = hit.Parent
		Debris:AddItem(tag,1)
		
        debounce = true -- ensures it will only run once, can be set to false to run again

	end
end)

You can disconnect a function from inside, as long as it’s defined first

local Test
Test = game.Workspace.ChildAdded:Connect(function(Child)
	Test:Disconnect()
	print(Child.Name)	
end)
4 Likes