For loop only returns one part when specifically programmed to return lots of part

So I’ve been working on this keycard reader animation thing, I specifically designed to work on every door with keycard readers, I used a for loop to search every keycard reader on each door, but It only applies to this specific door. How do I fix this?

Here is the code:

local player = game.Players.LocalPlayer
local db = false
local db2 = false

function findks()
	for i, v in pairs(workspace:GetChildren()) do
		if v.Name == "Door" and v:FindFirstChild("Keyslot") then
			local ks = v:FindFirstChild("Keyslot")
			local ks1 = ks:FindFirstChild("Base")
			if ks1 then
				return ks1
			end
		end
	end
end

while wait(0.1) do
	local part = findks()
	if part and player:DistanceFromCharacter(part.Position) < 10 then
		if part.Parent:FindFirstChild("InRange") then
			if not db then
				part.Parent:FindFirstChild("InRange"):FireServer()
				db = true
				db2 = false
			end
		end
	end
	if part and player:DistanceFromCharacter(part.Position) > 10 then
		if part.Parent:FindFirstChild("OutRange") then
			if not db2 then
				db = false
				db2 = true
				part.Parent:FindFirstChild("OutRange"):FireServer()
			end
		end
	end
end

Here’s what happens

door maker: wpzaza2f

I dont know who originally made the reference we were going for, we’re sorry.

Edit: I found the solution to this, I wasted my entire time using a local script when I could use server sided scripts and use BindableEvents, I’m so sorry everyone! :man_facepalming:

2 Likes

Whenever you return in a for loop, it stops looping through all the other instances.

1 Like

I got this error when I tried using that, any suggestions?

The 21st line is

 if part and player:DistanceFromCharacter(part.Position) < 10 then

I think the error originated from “part.Position”, I have little to no experience in tables, how do I fix this?

1 Like

Using return doesn’t stop the current thread, don’t spread false information.

Relevant: Programming in Lua : 4.4

You might wanna make a table for those parts and looping through the table of parts to alter them instead of returning

1 Like
function findks()
	local PartTable = {}
	for i, v in pairs(workspace:GetChildren()) do
		if v.Name == "Door" and v:FindFirstChild("Keyslot") then
			local ks = v:FindFirstChild("Keyslot")
			local ks1 = ks:FindFirstChild("Base")
			if ks1 then
				table.insert(PartTable,ks1)
			end
		end
	end
	return PartTable
end

this should work, instead of returning everytime it loops i put the parts in a table and returned that table c: (you might want to adjust the rest of the script so that it handles a table)