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

Need help understanding the ":Disconnect()" function - where do I place it?

Last night I couldn't figure out how to get a Touched connection to end when needed - someone suggested I use the :Disconnect() function. I looked into it and I can't quite figure out how to get it to work, adding it to my script just causes lag and a multitude of errors. I'm pretty sure I formatted the script wrong and put the :Disconnect() in the wrong spot, but I don't know where else to place it.

local connection
function onPunchDamageFired(Player)
	local rightArm = Player.Character:FindFirstChild("Right Arm")
	rightArm.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChild("Humanoid") and CanDmg == true and hit.Parent.Humanoid.Health > minimumhealth then
			hit.Parent.Humanoid:TakeDamage(dmg)
			CanDmg = false
			wait(1.5)
			CanDmg = true
			print 'punch succeeded'
		else
			print 'humanoid not found!'
		end
		connection:Disconnect()
	end)
	connection = rightArm.Touched:Connect(onPunchDamageFired)
end

punchdamageEvent.OnServerEvent:Connect(onPunchDamageFired)

1 answer

✓ Accepted answer

When calling the :Connect() method of RBXScriptSignal—ROBLOX's event base-class—it will allot the callback in an encapsulated function repository relative to the signal and its origin, then return an RBXScriptConnection object that illustrates its link to the said repository.

This object has a method called :Disconnect(), which effectively removes the callback from the repository.


On line 16, you do allocate the connection privy to that instruction but left another on line 04 unmanaged. You are actually contradicting your intentions by making that dual-connection, so I suggest you remove it and reform it to:

local function onPunchDamageFired(playerPunching)
	local signalConnection = nil --// Can be internally managed.
	--// ...
	signalConnection = rightArm.Touched:Connect(function(objectCollided)
		--// ...
		signalConnection:Disconnect()
	end)
end

punchDamageEvent.OnServerEvent:Connect(onPunchDamageFired)

####Side-note:

I see you are making a damage debounce, which is warranted, however, this will actually inhibit every other Player from making a swing as well. You should make a debounce dictionary instead. I also suggest that you don't make the connection to the .Touched event either if the debounce reads true.

2 comments

0

By hashmap do you mean dictionary? I have never heard of a hashmap before now.

0

Essentially.

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