How can I improve my stick script?

Hello! I made this script to stick parts and players who touch a specific block (script.Parent). How can I improve it?

local obj = script.Parent

obj.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		local savedProperties = {hit.Parent.Humanoid.WalkSpeed,hit.Parent.Humanoid.JumpPower}
		hit.Parent.Humanoid.WalkSpeed = 0
		hit.Parent.Humanoid.JumpPower = 0
		
		obj.TouchEnded:Connect(function(newHit)
			if hit == newHit then
				hit.Parent.Humanoid.WalkSpeed = savedProperties[1]
				hit.Parent.Humanoid.JumpPower = savedProperties[2]
			end
		end)
	else
		local weld = Instance.new("WeldConstraint")
		weld.Part0 = obj
		weld.Part1 = hit
		weld.Name = "Stick"
		weld.Parent = hit
		
		obj.TouchEnded:Connect(function(newHit)
			if hit == newHit then
				hit.Parent.Stick:Destroy()
			end
		end)
	end
end)
2 Likes

it looks pretty good to me :+1:

There’s actually a little problem with this script, using the TouchEnded event within the Touched event creates a memory leak.

What’s going to happen is that you will continue to create connections and the TouchEnded will trigger but not do anything.

To demonstrate this, I created a little script and threw it into a part

local i = 0

script.Parent.Touched:Connect(function(hit)
	if hit.Name == "RightFoot" then
		script.Parent.TouchEnded:Connect(function(removed)
			if removed.Name == "RightFoot" then
				i+= 1;
				print(i)
			end
		end)
	end
end)

Then I jumped on the part and watched as the increase in numbers jumped every time.

https://i.gyazo.com/0b7ea3d8b814557229c3c0bf675a2d07.mp4

(it is a tad bit buggy noted)

Anyways the solution would be to save the event in a variable and disconnect it when you don’t need it anymore!

script.Parent.Touched:Connect(function(hit)
    local event -- we need to put this outside so we can disconnect from the inside of the connect(function()
    event = script.Parent.TouchEnded:Connect(function(removed)
        if hit == removed then
            -- do stuff
            event:Disconnect() -- we disconnect the event
        end
    end)
end)
2 Likes