Find random child function timing out

I took your advice into consideration, and I believe I have altered my code to be both a bit shorter and better. It now will place a folder with the name of every player in the server inside a folder in ServerScriptService, then it will loop through it removing one each time that player has received and teleported to a plate. Here is the revised code:

function begin()
	for _,v in pairs(game:GetService("Players"):GetChildren()) do
		local p = Instance.new("Folder")
		p.Name = v.Name
		p.Parent = script.Parent.plrs
	end
	for _,v in pairs(script.Parent.plrs:GetChildren()) do
		local pl = frc(game:GetService("ReplicatedStorage").plates)
		pl.Parent = workspace.plates
		pl.Name = v.Name.."'s plate"
		workspace:FindFirstChild(v.Name):MoveTo(pl.Position)
		v:Destroy()
	end
end

You have it working efficiently now in terms of run time, but why the extra Folders? What is wrong with something like what’s below? Only the set you’re randomly picking from needs to be depleted.

function begin()
    local players = game:GetService("Players"):GetChildren()
    local plateStorage = game:GetService("ReplicatedStorage").plates
    for _,player in pairs(players) do
        if player.Character and player.Character.Parent == workspace then
            local plate = frc(plateStorage)
            plate.Parent = workspace.plates
            plate.Name = player.Name.."'s plate"
            player.Character:MoveTo(plate.Position)
        end
    end
end

You can loop through the players in any order, since the plate selection is randomized. Since the frc() function calls GetChildren() fresh each time, plates reparented to the workspace folder get removed from the pool for the next iteration.

While I’ve refactored your function a bit, it’s still not as complete or error-proofed as I’d normally make something like this. You should handle the case where a player hasn’t spawned or their Character model isn’t loaded when the function is called, because a player can join or leave at any time and you don’t want to try to move a non-existent Character.

1 Like