Select a random item from a folder

Hello! So, basically I want that so when a new player joins in the server, it choose a random grid and clone it for the player, so I made this code:

Players.PlayerAdded:Connect(function(player)
	local Plot = Instance.new("Folder", workspace.BuildingAreas)
	Plot.Name = player.Name
	wait(.1)

	for _,grids in pairs(ReplicatedStorage:WaitForChild("Building").Stored:GetChildren()) do
	local chosenGrid = grids[math.random(1, #grids)]
		local playerGrid = chosenGrid:Clone()
		playerGrid:WaitForChild("Avaliable").Value = false
		playerGrid.Parent = workspace:WaitForChild("BuildingAreas"):FindFirstChild(player.Name)
	end```

But when I go test it, I get this error: "attempt to get length of a Instance value"
How I can solve this? Any help is appreciated.

This should work

Players.PlayerAdded:Connect(function(player)
	local Plot = Instance.new("Folder", workspace.BuildingAreas)
	Plot.Name = player.Name
	wait(.1)

	for _,grids in pairs(ReplicatedStorage:WaitForChild("Building").Stored:GetChildren()) do
	local chosenGrid = grids:GetChildren()[math.random(1, #grids:GetChildren())]
		local playerGrid = chosenGrid:Clone()
		playerGrid:WaitForChild("Avaliable").Value = false
		playerGrid.Parent = workspace:WaitForChild("BuildingAreas"):FindFirstChild(player.Name)
	end

try to getchildren the folder and then do the math.random thing you did.

This is what I did in

for _,grids in pairs(ReplicatedStorage:WaitForChild("Building").Stored:GetChildren()) do

“Stored” is the folder that I want to get the grids

Tried this but now the grid did not even get cloned, no errors

What do you mean by didn’t get cloned: it hasn’t appered in the workspace folder or the playerGrid is nil?

Yah, it has’nt appeared in the workspace and did not get cloned in the folder

Would you mind sending a screenshot of how the Stored folder in replicated storage looks?

ReplicatedStorage:WaitForChild(“Building”).Stored:GetChildren()
image

If I understood you correctly, then you don’t need the for loop if you just want to get a random GridArea stored, like this:

game.Players.PlayerAdded:Connect(function(player)
	local Plot = Instance.new("Folder", workspace.BuildingAreas)
	Plot.Name = player.Name
	wait(.1)

	local grids = game.ReplicatedStorage:WaitForChild("Building").Stored:GetChildren()
	local chosenGrid = grids[math.random(1, #grids)]
	local playerGrid = chosenGrid:Clone()
    playerGrid:WaitForChild("Avaliable").Value = false
	playerGrid.Parent = workspace:WaitForChild("BuildingAreas"):FindFirstChild(player.Name)
end)
1 Like

Oh, it works I think it could not be this way
Thank you.

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