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