Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
Admin8483 -21
7 years ago
Edited 7 years ago

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))
0
One second lemme write this up. Cyrakohl 108 — 7y

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

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.

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. ScriptGuider 5640 — 7y
Ad

Answer this question