How to choose a player that's alive?

I have this script that chooses a random player to say a dialogue, but it also chooses a random player that is dead. I already made it where you’re on the Alive team but if you die you go to the Dead team. How do I make it where if the player dies he doesn’t get chosen?

--Variables
local remotes = game.ReplicatedStorage.Remotes
local CreateDialogueEvent = remotes.CreateDialogueEvent

local randomPlayerName
local randomPlayerId

local function getPlayerImage(player_id)
	local content, isReady = game:GetService("Players"):GetUserThumbnailAsync(player_id, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size420x420)
	return content
end



local function getRandomPlayer()
	local players = game.Players:getPlayers()
	local number = math.random(1,#players)
	local randomPlayer = players[number]
	randomPlayerName = randomPlayer.Name
	randomPlayerId = randomPlayer.UserId
end

--Actual Game Script

local function challenge_1()
	local noimage = "rbxassetid://0"
	wait(2)
	CreateDialogueEvent:FireAllClients(getRandomPlayer(getPlayerImage),"Finally made it to the new house.")
end

local function challenge_2()

end

local function challenge_3()

end

local function challenge_4()

end

local function challenge_5()

end

local function challenge_ending()

end

local function startGame()
	challenge_1()
	challenge_2()
	challenge_3()
	challenge_4()
	challenge_5()
	challenge_ending()
end

wait(4)
startGame()

Try this

function getRandomPlayers()
   local rawplayers = game.Players:GetPlayers()
   local players = {} 
   for _,player in pairs(rawplayers) do
        if player.Character then table.insert(players, player)
   end
   —[[the random player code can go here—]]
end 

The rawplayers table contains all players regardless of whether they are alive or dead. The players table only contains players who are alive by checking if their character exists. The character won’t exist if the player is dead

1 Like

Hi Techno_Blazes, you can get the array of players from the ‘Alive’ team using ‘Team:GetPlayers()’
Your code could looks like;

local AliveTeam = game.Teams.Alive -- You might need to change this depending on your team name.
local function getRandomPlayer()
	local players = AliveTeam:GetPlayers()
	local number = math.random(1,#players)
	local randomPlayer = players[number]
	randomPlayerName = randomPlayer.Name
	randomPlayerId = randomPlayer.UserId
end

Hope this helps.

2 Likes

Yeah this one is more suited than my solution

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.