How can I fix attempt to index nil with 'Connect'

Hello, I have this error message. Idk how to fix is it because I want to use a touch event on a table? but I also dont know how to use a touch event on a table.
this is the code:

local coin = game:GetService("CollectionService"):GetTagged("Coins")
local storage = game:GetService("ReplicatedStorage")
debounce = false

coin.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	
	if debounce == false then
	if humanoid then
debounce = true
		local player = game.Players:GetPlayerFromCharacter(humanoid.Parent)
		player.leaderstats.Coins.Value += 1
		
		storage.CoinRemoteEvent:FireClient(player)
		
		wait(120)
		
		debounce = false
	end
    end
end)

any help is appreciated!

1 Like

coin here is a table of objects not one singular object so it doesnt have the Touched event, try using a for loop instead

1 Like

I did it like this:

local coin = game:GetService("CollectionService")
local storage = game:GetService("ReplicatedStorage")
debounce = false

for i, Coins in pairs(coin:GetTagged("Coins")) do
	
	Coins.Touched:Connect(function(hit)
		local humanoid = hit.Parent:FindFirstChild("Humanoid")

		if debounce == false then
			if humanoid then
				debounce = true
				local player = game.Players:GetPlayerFromCharacter(humanoid.Parent)
				player.leaderstats.Coins.Value += 1

				storage.CoinRemoteEvent:FireClient(player)

				wait(120)

				debounce = false
			end
		end
	end)
	
end

but now nothing happens when i touch a coin
sorry im not good at for loops

1 Like