Problem with Humanoid:MoveToFinished

Got a weird bug with my script and I don’t know what’s going on.

I’ve got a script that detects when a player clicks a part, fires an event to a server script, where the server script then moves the player to the part the player just clicked.

Problem is, the Humanoid: MoveToFinished function repeats itself weirdly. If I run the script once, the player walks to the script, and the function prints “Done” correctly, and only once as it should.

But the second time I ran the script and walked to the part in the same game instance, the function prints “Done” twice. I tried for the third time, it printed “Done” 3 times. So, for some reason, the function is playing itself again for the number of times I have re-run the script.

Can anyone figure this strange bug out? Here is the script:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(Player)
	local Folder = Instance.new("Folder")
	Folder.Name = Player.Name.."-Fruit"
	Folder.Parent = workspace
end)

local Num = 0

ReplicatedStorage.PickedFruit.OnServerEvent:Connect(function(Val1,Val2,Val3)
	local Distance = (Val3.HumanoidRootPart.Position - Val2.Position).magnitude
	if Distance < 30 and Distance > 4 then
		Val3.Humanoid:MoveTo(Val2.Position - CFrame.new(Val3.HumanoidRootPart.Position, Val2.Position).LookVector * 4)
		
		Val3.Humanoid.MoveToFinished:Connect(function() -- Here is our buggy function
			print("Done")
		end)
		
	end
end)

Thanks for your time!

Do you have any errors in the output?

You a mare connecting the event every time you move without disconnecting it so it runs multipul times

Nope, there are no errors occuring

Oh, okay. Except how do I disconnect a function?

Put this at the bottom of your code

Use local function = connect blah
Function:disconnect()

Unless you do this which is better

local Function

local function MoveToFinished()
	print("Done")
	Function:Disconnect()
end
Function = Val3.Humanoid.MoveToFinished:Connect(MoveToFinished)

Fixed it, and heres the updated code. Thanks for your help!

No problem happy to help! :slight_smile: