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

selecting random player but interval is empty?

Asked by 2 years ago

So I am making a game where you have to find the treasure chest and i want a series of random events to happen for example: a random player gets faster

but im trying to get the random player on this script right here

local Players = game:GetService("Players"):GetChildren()

game.Players.PlayerAdded:Connect(function(player)
    wait(0.5)
    player.CameraMaxZoomDistance = 17

    wait(5)
    local randomplayer = Players[math.random(1, #Players)]
    randomplayer.Character.Humaniod.WalkSpeed = 30
end)

the other part is for max zoom distance the error is saying 11:32:28.929 ServerScriptService.MaxZoomDistance:8: invalid argument #2 to 'random' (interval is empty) - Server - MaxZoomDistance:8

1
Mate, you're grabbing the in-game players way too early; there's nobody in the server at that time. That array will not update either. TL;DR: Grab the players within your PlayerAdded listener Ziffixture 6913 — 2y
0
i figured it out but ur comment still makes sense and will help me ragdollkiiing2 19 — 2y

1 answer

Log in to vote
0
Answered by 2 years ago

You need to take a look on math.random(). It takes interval of numbers (x to y) and chooses random one among them, it needs interval which are numbers between that two numbers. But if first player joins, there is only one player in game.Players, which means it will be math.random(1,1), which is not interval. You got zero numbers between that 2 numbers, that interval is nil, its empty. What is more you defined Players at the top of the script which means it will be zero forever, beecause it wont get updated when player joins!. Here is the solution:

local Players = game:GetService("Players")
local numOfPlayers = 0

local function onPlayerAdded(player)
    numOfPlayers = #Players:GetPlayers() -- get number of players in game

    player.CameraMaxZoomDistance = 17
    local randomPlayer

    if numOfPlayers > 1 then
        randomPlayer = Players:GetPlayers()[math.random(1, numOfPlayers)]
        randomPlayer.Character:WaitForChild("Humanoid").WalkSpeed = 30
    end
end


Players.PlayerAdded:Connect(onPlayerAdded)
Ad

Answer this question