How can I make this work? (Part face part)

Basically I’m trying to make this part continuously face a random player. But it errors if there is no players in the game. How can I fix this? How do I wait for players to exist to run this loop and make sure there is players in the game?

local p1 = script.Parent

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

if (players.NumPlayers > 0) then

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

end
1 Like

You could you use a repeat until loop.


local amtPlayers = #game.Players:GetPlayers()

repeat wait(1)
	amtPlayers = 0
	for i, v in pairs(game.Players:GetPlayers()) do
		amtPlayers += 1
	end
until amtPlayers >= 2 -- Change to any number