Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

FindFirstChild giving error when checking if object exists?

i'm having a huge headache with this. Its something that usually works without problem but in this case it throws an error. This part of my master script is supposed to check if the object "LoadDone" exists inside each player and if its nil remove them from the table so they don't join the round. I can't publish the whole script as it is 300 lines long and i'm working for someone.

ty=game.Players:GetPlayers()
for x=1,#ty do
found=ty[x]:FindFirstChild("LoadDone")
if not found then
table.remove(ty,x)
end
end

it returns the error

09:06:57.617 - ServerScriptService.MasterScript:27: attempt to index field '?' (a nil value)
09:06:57.618 - Stack Begin
09:06:57.618 - Script 'ServerScriptService.MasterScript', Line 27
09:06:57.619 - Stack End

line 27 translates to line 3

2 answers

✓ Accepted answer

Hey luke, I think that if you try this type of loop, it might work

ty=game.Players:GetPlayers()
for i,x in pairs(ty) do --equivillant of "for i,v in pairs"
	found = x:FindFirstChild("LoadDone")
	if not found then
		table.remove(ty,x)
	end
end

Hope I helped

The problem is that you are removing entries from the ty loop while you are traversing it, which causes the index to eventually be greater than the length of the table. You need to create a separate table and add entries which do have LoadDone in them instead, like this:

local ty = {}
for i, v in ipairs(game.Players:GetPlayers()) do -- Use a pairs/ipairs loop for traversing tables.
	if v:FindFirstChild("LoadDone") then
		table.insert(ty, v)
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.