.Touched on new instances

Hello, I currently have a script where when a part is created with instance.new() I have a .Touched event connected to that new instance. The touched event is supposed to add coins on to the player. The problem I have is first of all when a part is touched it fires multiple times because a player touches the part multiple times. The fix I thought I would have for that was to add a debounce although a debounce fixes my original issue and now only gives one coin it creates a new one. Since all the instances are connected to the same function a debounce disables the other parts from getting that touched function until the debounce has ended. Is there a way I can solve this issue without having to put a script of this inside every new instance that is created?

for anyone wondering this is how I have my code set up right now, Ignore the fake variables

for i,v in pairs(alltheparts)
      v.Touched:Connect(function()
end)
end

Make sure you provide an argument inside the function, which will check who has touched it, make sure that object has a humanoid in.

[Because from the code you provided, I can tell you forgot to put that argument]

I didnt put the whole script in it it was just to show how it was set up, in the actuall script I have it, it works but it has the issue I explained in the long essay above it lol

local parts = game.Workspace.Folder:GetChildren()
local delayTime = 5


for i,v in pairs(parts ) do
	local debounce = false
    v.Touched:Connect(function()
		if debounce then return end
		debounce = true
		print("hi")
		task.wait(delayTime )
		debounce = false
	end)
end

Forgive me, your question seemed to be a bit confusing, so I misunderstood you, fixed it.

You should only apply the debounce inside the loop.

for i,v in pairs(alltheparts) do
	local debounce = false
    v.Touched:Connect(function()
		if debounce then return end
		debounce = true
		onTouched() --your code to add coins on to the player
		tasks.wait()
		debounce = false
	end)
end

See the problem is when do it this way
https://gyazo.com/0ad00619ac8eb17ace5c7d6995e260c0
it skips some coins because the debounce is active

should have worked, since an event and its debounce are created for each part separately.

On the other hand, if your script is a Server Script then your issue is probably due to the lag.

Yeah, after some more testing I think server lag is the problem, thanks for the help :smiley: