Help with function script

Hello,
I’ve created a subroutine that takes 3 parameters and an event function inside the subroutine utilising one of the parameters which is constantly changing but for some reason the event sometimes executes despite the parameter changing but the .Touched event hasn’t updated. See comments in the code for further details.

local function damage(plr, arm, dmg) -- assuming that right arm is the parameter for arm
	print(arm.Name) -- prints "Right Arm"
	arm.Touched:Connect(function(otherPart) -- Fires for "Left Arm".Touched
		if otherPart.Parent.Humanoid ~= nil and otherPart.Parent.Name ~= plr.Name then
			print(arm.Name.." hit "..otherPart.Name) -- prints "Left Arm" instead
		end
	end)
end

Output:
image

The connection isn’t “Updated” it’s adding more connections, you have two connections not one and every time you call damage you will add another. One can create millions of connections on the same part until the server crashes. You need to either find a way to disconnect your connections or avoid them entirely.

This example code will disconnect the arm.Touched connection after it prints once.

local function damage(plr, arm, dmg)
	print(arm.Name)
    local connection: RBXScriptConnection -- declare a empty connection variable
	connection = arm.Touched:Connect(function(otherPart)
		if otherPart.Parent.Humanoid ~= nil and otherPart.Parent.Name ~= plr.Name then
			print(arm.Name.." hit "..otherPart.Name)
            connection:Disconnect() -- stop this connection after print
		end
	end)
end
1 Like