What is the best way to get all of the players characters in the game?

Hey, I want to re-optimize some old and new scripts.

I have been using 2 ipair loops to get the children of workspace, and then I would use another on to get the children of Players, and then I would check if their names are the same. And if they were, I would do whatever I would do after that.

But I want to re-optimize the script and make it look more clean, professional, and use less memory and keep a good FPS for the player.

2 Likes
-- well you could just:
for i,v in pairs(game.Players:GetPlayers()) do
    local Char = v.Character
end
2 Likes

You could have a folder named “PlayerCharacters”, and each time the player has joined, put his character there.

1 Like

I feel like that would be a good way to confuse exploiters also, because they may only try looking for there player character in the workspace.

you can insert the players into a table like so,

local Players = {}
game.Players.PlayerAdded:Connect(function(plr)
table.insert(Players,plr)
local Char = plr.Character or plr.CharacterAdded:Wait()
Char.Humanoid.Died:Connect(function()
table.remove(Players,table.find(Players,plr))
end)
end)
game.Players.PlayerRemoving:Connect(function(plr)
table.remove(Players,table.find(Players,plr))
end)
1 Like
local players = game:GetService("Players")

local function getCharacters()
	local characters = {}
	for _, player in pairs(players:GetPlayers()) do
		local character = player.Character
		if typeof(character) == 'Instance' and character:IsA("Model") then
			local humanoid = character:FindFirstChildWhichIsA("Humanoid")
			if typeof(humanoid) == 'Instance' and humanoid:IsA("Humanoid") and humanoid.Health > 0 then
				table.insert(characters, character)
			end
		end
	end
	return characters
end

Get all of the player characters in your game that are not dead.