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

Choosing a player?

Asked by 8 years ago

Hello. I tried to pick an "alien" from a table of players. It's not working. The error says:

18:43:22.097 - ServerScriptService.GameScript:15: bad argument #2 to 'random' (interval is empty)

This is my code:

local playerstorage = game:GetService("Players")
local players = {}

while true do

for _, player in pairs(game.Players:GetPlayers()) do
            if player and player.Character then
                local humanoid = player.Character:WaitForChild("Humanoid")
                if humanoid and humanoid.Health > 0 then
                    table.insert(players, player)
                end
            end
        end

local alien = players[math.random(1, #players)]

wait(0.1)
end

1 answer

Log in to vote
3
Answered by 8 years ago

That just means that the 2nd argument in the math.random function is smaller than the 1st argument. Basically, the script is running when there are no players in the game.

To fix this, simply add a conditional that checks to see if the game has at least 2 players, to prevent errors, like so:

local playerstorage = game:GetService("Players")
local players = {}

while true do
    for _, player in pairs(game.Players:GetPlayers()) do
        if player and player.Character then
            local humanoid = player.Character:WaitForChild("Humanoid")
            if humanoid and humanoid.Health > 0 then
                table.insert(players, player)
            end
        end
    end
    if #players >= 2 then
        local alien = players[math.random(1, #players)]
        --More code
    end
    wait(0.1)
end

Hope this helped!

More info: math.random

0
Thanks so much!!!! fight4money -2 — 8y
0
Only one problem: multiple players are chosen! fight4money -2 — 8y
Ad

Answer this question