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

Selecting random players gives error?

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.

1 comment

0

what you're doing wrong is trying to use selectedindex which is actually just a number value as the player.

2 answers

✓ Accepted answer

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()

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.

1 comment

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.

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