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

Selecting random players gives error?

Asked by 5 years ago

Here's the script:

local repstorage = game:GetService("ReplicatedStorage")
local players = game:GetService("Players")

function pickPLR()
    local plrlist = players:GetChildren()
    local selectedIndex = math.random(1,#plrlist)
    local target = CFrame.new(158.5, 44.5, 77.5)
    selectedIndex.Character.HumanoidRootPart.CFrame = target
end

while true do
    wait(5)
    pickPLR()
    wait(50)
end

Now when I test this it tells me "Attempt to index local 'selectedIndex' (a number value)"

Can anyone tell me what i'm doing wrong? The point of the script is to select a random player and teleport only that player to the target area.

0
what you're doing wrong is trying to use selectedindex which is actually just a number value as the player. Elixcore 1337 — 5y

2 answers

Log in to vote
0
Answered by 5 years ago

Your problem is really simple, actually. In your code, selectedIndex is set to a number, not the player that was randomly chosen. To fix this, just use selextedIndex to index the table of players, so in this case plrlist.

The fixed code should look like this:

local repstorage = game:GetService("ReplicatedStorage")
local players = game:GetService("Players")

function pickPLR()
    local plrlist = players:GetPlayers()
    local selectedIndex = math.random(1,#plrlist)
    local target = CFrame.new(158.5, 44.5, 77.5)
    plrlist[selectedIndex].Character.HumanoidRootPart.CFrame = target
end

while true do
    wait(5)
    pickPLR()
    wait(50)
end

I also changed :GetChildren() to :GetPlayers()

Ad
Log in to vote
0
Answered by
Fifkee 2017 Community Moderator Moderation Voter
5 years ago

You're trying to index a numbervalue, like it says. Not a player.

Use :GetPlayers() to create a table of all the players in your game, and then math.random that, like so.

function pickRandomPlayer()
    local Players = game:GetService('Players'):GetPlayers()
    local SELECTED_PERSON = Players[math.random(1, #Players)]
    local TARGET = CFrame.new(158.5, 45.5, 77.5) --Note, don't spawn the player at the part's exact Y position, set it a few studs over. It'll get them stuck very often.
    SELECTED_PERSON.Character:WaitForChild('HumanoidRootPart').CFrame = TARGET
    return SELECTED_PERSON
end

while wait(5) do
    pickRandomPlayer()
    wait(50)
end

The reason this works is because GetPlayers, GetChildren, and GetDescendants return a table. Then, you can pick a random index out of all the players by picking randomly between 1, the first player, and #Players, the length of the table.

0
Also, you might want to put the while wait(5) do into a spawn, because at some point you may want to extend the script. As far as I know, while loops halt the current thread that it's in. Fifkee 2017 — 5y

Answer this question