Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Help with error Workspace.Script:3: attempt to index local 'randomPlayer' (a nil value)?

I do not know how to fix this error, and I need help, because I don't know what to change.

local Players = game.Players:GetPlayers()
local randomPlayer = Players[math.random(1, "10")]
randomPlayer.Character:MoveTo(Vector3.new(-33.2, 10.15, 168.2))

1 comment

0

One second lemme write this up.

1 answer

The second line of code is probably trying to assign a variable to a player that doesn't exist. If there are only two players in the game, trying to get the 10th player will return nil. Instead, the second line of code should look like this:

local randomPlayer = Players[math.random(1, #Players)]

"#Players" is the length of the "Players" table, which is how many players there are.

Also, while I don't think it's breaking the script, the second argument for math.random() should be a number, not a string.

1 comment

0

Just a little tip for anyone reading, you can (and should) use the NumPlayers property of the Players service instead of using the list length of GetPlayers.

This discussion is preserved as it was. New answers, comments, and votes are closed.