Why wont the i,v in pairs loop run?

I’m currently using in pairs loop to trigger an event when one of the parts in a folder in the workspace gets touched by a player, then the part should fade away and for some reason it doesn’t work. What could be the solution?

My script:

local tiles = game.Workspace.Tiles:GetChildren()
local debounce = true

for i, v in pairs(tiles) do
	game.Workspace.Part.Touched:Connect(function(hit)
		local player = hit.Parent:FindFirstChild("Humanoid")

		if player and debounce == true then
			debounce = false
			 v.Transparency = 0.5
               wait(1)
             v.Transparency = 1
             v.CanCollide = false
             wait(3)
             v.Transparency = 0
             v.CanCollide = true
             debounce = true
			
		end
	end)
	
end

  1. You should add a WaitForChild to Tiles, it is possible it havent loaded in to the game yet.
    Additionally, maybe add a print statement in your code, to narrow down the issue to your for loop or another potential factor.
1 Like

Where do i add waitforchild to the tiles?

What type of script is this? A localscript or script? Where is it at?

a script in the servicescriptservice

You should consider moving the loop inside the connection. Connecting the same event for every “tile” is bad practice. Likewise, for the array of children you’ll want to use ipairs, not pairs, though that wouldn’t prevent it from running.

What makes you believe the loop doesn’t run? Have you tried printing a statement inside the loop and also printing the size of tiles?

Okay, obvious mistake at:

	game.Workspace.Part.Touched:Connect(function(hit)

Change it to:

	v.Touched:Connect(function(hit)

You’re defining a random part rather than the actual object you want to fade.

How would that even work? How would you detect touches on multiple parts through a single event

Just a sidenote but you should try to use ipairs instead of pairs when faced with a table indexed by integers with no holes in it. The table returned by Instance:GetChildren() and similar methods are good examples of this.

If you actually look at the code, they connect the same part every time, game.Workspace.Part

The debounce means it will only work for 1 tile, but it appears the intention is to do an action on all tiles when the part is touched, hence my reply.

If the intention is to connect to each tile, then that is obviously a mistake in their code and my reply will probably highlight that flaw, though it is even more explicit now.

I did already mention this in my earlier reply. Make sure to read the existing replies.

2 Likes