FindFirstChild Returns Nil

uhh yes…

so i have this loop which spawns players in random rooms…

it loops through a folder called “Rooms” in workspace and chooses a random number between 1 and the length of the table.
now when it finds a child it checks first if the IndexNumber is the same as the chosen number and if it is, it checks if it’s a model , then it looks for a part called “Floor” and spawns the player’s character there.
but for some reason it returns nil when looking for “Floor” which is strange since i’ve checked and in every room there’s at least 1 part Called Floor with capital F and everything.

for i,v in pairs(game.Players:GetPlayers()) do
		v.Character.Humanoid.JumpPower = 0
		v.Character.Humanoid.JumpHeight = 0
		
			local RandomNumber = math.random(1,#workspace.Rooms:GetChildren())
			for I,Room in pairs(workspace:GetChildren()) do
				if I == RandomNumber then
					if Room:IsA("Model") then
						local SpawnPart = Room:FindFirstChild("Floor") or Room:FindFirstChild("RoomBaseModel"):FindFirstChild("Floor")
						if SpawnPart then
							v.Character.PrimaryPart.Position = SpawnPart.Position + Vector3.new(0,2,0)
						end
					end
				end
			end
	end

so the or is because it could be just in the model or it could be in another model inside of that model called “RoomBaseModel” which would contain the walls and floors and roofs etc…

thanks in advance!

It’s actually looping through the whole workspace:

for I,Room in pairs(workspace:GetChildren()) do

so you probably just need to change it to workspace.Rooms:GetChildren()

2 Likes

I know you’ve already marked my initial reply as Solved to your problem but I just wanted to add - you don’t need the loop to find the randomly selected room, you could do it like this:

for i,v in pairs(game.Players:GetPlayers()) do
	v.Character.Humanoid.JumpPower = 0
	v.Character.Humanoid.JumpHeight = 0
	
	local Rooms = workspace.Rooms:GetChildren()
	local RandomNumber = math.random(1,#Rooms)
	if Rooms[RandomNumber]:IsA("Model") then
		local SpawnPart = Rooms[RandomNumber]:FindFirstChild("Floor") or Rooms[RandomNumber]:FindFirstChild("RoomBaseModel"):FindFirstChild("Floor")
		if SpawnPart then
			v.Character.PrimaryPart.Position = SpawnPart.Position + Vector3.new(0,2,0)
		end
	end

end

oh i didn’t know, i’ve always used loops to find the number, i guess i am not the most efficient programmer.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.