I’m very little experienced with math.random, so dont judge me please.
“Attempt to get length of a Instance value”
When i try my script to select a random player, it throws up the above error.
Code:
while true do
wait(.2)
-- Required Stuff
local inRound = game.ReplicatedStorage.InRound
local playerValue = game.ReplicatedStorage.Players
local status = game.ReplicatedStorage.Status
-- Starting
wait(1)
status.Value = "Starting in 5"
wait(1)
status.Value = "Starting in 4"
wait(1)
status.Value = "Starting in 3"
wait(1)
status.Value = "Starting in 2"
wait(1)
status.Value = "Starting in 1"
wait(1)
status.Value = "Starting in 0"
wait(1)
status.Value = "Starting.."
wait(1)
-- Loading Stuff
local fight = game.ServerStorage.JudgementHall:Clone()
fight.Parent = workspace
local spawns = fight:WaitForChild("Spawns")
-- Changing teams
-- Selecting CHARAS.
for i, player in pairs(game.Players:GetPlayers()) do
if player then
player.TeamColor = BrickColor.new("Really red")
end
-- Selecting SANS.
for i, player in pairs(game.Players:GetPlayers()) do
local chooseSans = math.random(1, #player)
if chooseSans.TeamColor == "Smoky grey" or chooseSans.TeamColor == "Really red" then
chooseSans.TeamColor = BrickColor.new("Cyan")
end
end
end
end
To select a random player, you need to do three things:
Get a Table of Player instances
local players = game.Players:GetPlayers()
Generate a random number between 1 and a the number of players. This is where your mistake is. You’re attempting to get the length of a player (huh?), not the length of the list of players.
local randomIndex = math.random(#players)
Use that randomly generated number to index the table of players
local randomlySelectedPlayer = players[randomIndex]
Full demonstration of the code may look something like this:
local players = game.Players:GetPlayers()
local randomIndex = math.random(#players)
local randomlySelectedPlayer = players[randomIndex]
if randomlySelectedPlayer.TeamColor == "Smoky grey" or randomlySelectedPlayer.TeamColor == "Really red" then
randomlySelectedPlayer.TeamColor = BrickColor.new("Cyan")
end
wait(1)
status.Value = "Starting in 5"
wait(1)
status.Value = "Starting in 4"
wait(1)
status.Value = "Starting in 3"
wait(1)
status.Value = "Starting in 2"
wait(1)
status.Value = "Starting in 1"
wait(1)
status.Value = "Starting in 0"
wait(1)
status.Value = "Starting.."
wait(1)
is not very nice to look at, there is an obvious improvement you can make here! Consider the use of a loop. This whole snippet of code can be shortened into five lines!
There’s a general concept in programming called DRY - Don’t Repeat Yourself. Usually, whenever you’re writing code that’s very similar, there’s a programming method you can use to shorten the code
for countdown = 5, 0, -1 do
wait(1)
status.Value = "Starting in " .. tostring(countdown)
end
status.Value = "Starting..."