In pairs loop problem - Script Error

Hello,

I am trying to make random parts turn on fire and once I click the fire is put out. I came across a problem with math.random in an in pairs loop. I have been looking around the forum and could find the same problems but I couldn’t replicate their fixes. Thank you.

Error: invalid argument #1 to ‘pairs’ (table expected, got Instance)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local partFolder = ReplicatedStorage:FindFirstChildWhichIsA("Folder")
local Availableparts = partFolder:GetChildren()

local parts = Availableparts[math.random(1,#Availableparts)]

partFolder.Parent = workspace


for i, x in pairs(parts) do
	
	local fire = Instance.new("Fire")
	local clickdetector = Instance.new("ClickDetector")
	
	
	fire.Parent = x
	clickdetector.Parent = x
	
	
	clickdetector.MouseClick:Connect(function()
		
		fire:Destroy()
		
	end)
	
	wait(1)
end

Thanks,

Ultan

1 Like

Use parts:GetChildren() to iterate through the children, it’s attempting to iterate through an instance which can’t be iterated through.

2 Likes

oh so are you trying to set a random part on fire every one second?
if im right, can you try removing the math.random line and replace the in pairs(parts) with in pairs(Availableparts)
like this

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local partFolder = ReplicatedStorage:FindFirstChildWhichIsA("Folder")
local Availableparts = partFolder:GetChildren()

partFolder.Parent = workspace


for i, x in pairs(Availableparts) do
	
	local fire = Instance.new("Fire")
	local clickdetector = Instance.new("ClickDetector")
	
	
	fire.Parent = x
	clickdetector.Parent = x
	
	
	clickdetector.MouseClick:Connect(function()
		
		fire:Destroy()
		
	end)
	
	wait(1)
end

its already going to the parts one by one per second so you dont need the math.random()
i haven’t tested it yet so it may not work.

1 Like

Try this, it should work:

local Availableparts = partFolder:GetChildren()
partFolder.Parent = workspace

for i = 1, #Availableparts do

	local fire = Instance.new("Fire")
	local clickdetector = Instance.new("ClickDetector")
	local part = Availableparts[math.random(1, #Availableparts)]

	fire.Parent = part
	clickdetector.Parent = part

	clickdetector.MouseClick:Connect(function()
		fire:Destroy()
	end)
	wait(1)
end
1 Like