MoveToFinished is triggered once more with each run

After I press the ProximityPrompt, the player character should go to a special place and an event is triggered when I arrive there.

However, I noticed that every time I press the ProximityPrompt and arrive there, the event is triggered twice, three times and so on. After looking into why this is, I found out that it is because of the humanoid.MoveToFinished.

I looked for a possible solution, but I couldn’t find anything that could possibly help me.

--
local debounce = false
ProximityPrompt.Triggered:Connect(function(player)
	print("1")
	if debounce == false then
		debounce = true
		local character = player.Character
		local humanoid = character:FindFirstChild("Humanoid")
		local torso = character:FindFirstChild("LowerTorso")
		local leftHand = character:FindFirstChild("LeftHand")

		if character and humanoid and torso and leftHand then
			local path = PathFindingService:CreatePath()
			path:ComputeAsync(torso.Position, targetPlate.Position)
			humanoid:MoveTo(targetPlate.Position)

			humanoid.MoveToFinished:Connect(function()
				print("2")
				local Weld = Instance.new("Weld", leftHand)
				Weld.Part0 = leftHand
				Weld.Part1 = takeInHandPart
				PutPlateOnBack(humanoid, torso)
				TakePlateGUIRE:FireClient(player)
			end)
		end
	end
end)


TakePlateGUIRE.OnServerEvent:Connect(function()
	debounce = false
end)

You are creating multiple .MoveToFinished events without disconnecting the previous ones. Every time the player is using the prompt, an extra connection is binded to the humanoid on top of the previous connection. So it would trigger once the first pass, then twice, then three times, etc.

Think of connections as creating a part and putting it inside of your humanoid. You need to clear it once you’re done with it.

local myConnection: RBXScriptConnection
myConnection = humanoid.MoveToFinished:Connect(function()
	print("disconnecting the event, code below will execute, but this event will no longer trigger again")
	myConnection:Disconnect()

	print("2")
	local Weld = Instance.new("Weld", leftHand)
	Weld.Part0 = leftHand
	Weld.Part1 = takeInHandPart
	PutPlateOnBack(humanoid, torso)
	TakePlateGUIRE:FireClient(player)
end)
3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.