Trying to get a random player

Hi! So I’m trying to make a script that makes it so that an AI moves to a random player each 100 seconds. The problem is that I get the error in the output “(Interval is empty)”.
Script:

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

while true do
	local randomPlr = players[math.random(1,#players)]
	script.Parent.Humanoid:MoveTo(randomPlr.Character.HumanoidRootPart)
	print("New Player is getting followed")
	wait(100)
end

Any help is appreciated!

You need to check if the length of players is greater than zero.

1 Like

Move local players = game:GetService("Players"):GetPlayers() inside of the loop so that way it always gets the current amount of players when you need it, as right now it only gets the players that were here since the server started and never check again, which will be 0 even if a player joined

Though I would also recommend putting a Players.PlayerAdded:Wait() before you start the loop to ensure that at least 1 player exists

game:GetService("Players").PlayerAdded:Wait()

while true do
	local players = game:GetService("Players"):GetPlayers()
	local randomPlr = players[math.random(1,#players)]
	script.Parent.Humanoid:MoveTo(randomPlr.Character.HumanoidRootPart)
	print("New Player is getting followed")
	wait(100)
end

And minor thing, I would recommend the usage of task.wait instead of wait as it’s the more modern and improved method

The error goes away, but now a new one pops up. It’s the typical “attempt to index nil with “HumanoidRootPart””.

Try this: (Whenever you use MoveTo() it has to go to a vector3, it can’t just move to the hrp)

game:GetService("Players").PlayerAdded:Wait()

while true do
	local players = game:GetService("Players"):GetPlayers()
	local randomPlr = players[math.random(1,#players)]
local rplr = randomPlr.Character or randomPlr.CharacterAdded:Wait()
	script.Parent.Humanoid:MoveTo(rplr:FindFirstChild(HumanoidRootPart).Position)
	print("New Player is getting followed")
	wait(100)
end

Thanks! It worked! Now I just need to find out why the model doesn’t move, but the script is working fine.

1 Like

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