How do I wait for players to load in before a script runs? (Other than just using a wait command?)

I have an issue with my code, when I press run. The script runs before the players are loaded in causing an error in the math.random interval. How do I wait for players to load?

local p1 = script.Parent

local players = game:GetService("Players"):GetPlayers()

local p2P = players[math.random(1,#players)]

local p2 = p2P.Character:WaitForChild("Head")

while true do

task.wait(1)

for i = 1,100 do

p1.CFrame = p1.CFrame:lerp(CFrame.new(p1.Position, p2.Position), i/100)

wait()

end

end

Is there a specific count of players that you are waiting for?
In that case you can do

while #game.Players:GetPlayers() < count do
   task.wait (0.5)
end

You can use this:

local players = game:GetService(“Players”)

players.PlayerAdded:Connect(function(player)
   player.CharacterAppearanceLoaded:Connect(function()
     —— your code here
    end)
end)

You can learn more about CharacterAppearanceLoaded here

local players = game:GetService("Players")

local flag = false

local function doRound()
	--Code here.
end

players.PlayerAdded:Connect(function(player)
	if not flag then
		if #players:GetPlayers() >= 2 then
			flag = true
			doRound()
		end
	end
end)

Please set this as the Solution :hugs:

1 Like

You could use the CharacterAppearanceLoaded event.