How to make it random player highest chance if someone leaving the game?
I have a code here below
local playerSS = game:GetService("Players")
function randomPlayer()
local highestChance = 0
local chosen
local chosenChar
for i, plr in pairs(playerSS:GetPlayers()) do
local ChanceToBeMonster = plr:WaitForChild("ChanceToBeMonster")
if ChanceToBeMonster.Value >= highestChance then
highestChance = ChanceToBeMonster.Value
chosenChar = plr
chosen = plr.Name
end
end
ChosenPlayer.Value = chosen
return chosenChar
end
playerSS.PlayerRemoving:Connect(function(plr)
randomPlayer()
end)
There’s a few problems with your code that would error in runtime. You also have to break the loop so that once you have the “ChosenPlayer” there isn’t a next iteration that will change it back.
you fail to do it here:
Here’s a refactor:
local players: {Player}
local function getNewRandomMonster()
players = Players:GetPlayers()
for _, player in players do
--[[
consider adding a check to ignore the current monster
if that falls under the vision you have for the game
highestChance is missing, not sure how your code works.
]]
local ChanceToBeMonster = plr:WaitForChild("ChanceToBeMonster")
if ChanceToBeMonster.Value >= highestChance then
highestChance = ChanceToBeMonster.Value
return player.Name
end
end
-- this is a fallback in case the code above didn't succed picking a random monster.
-- this is how you write more robust code, by minimizing the errors.
local randomindex = math.random(#players)
return #players > 0
and randomindex <= #players
and players[randomindex].Name
end