How to get children from players and use in workspace

Example of what I want it to become:
image

I’m working on a gun game, and there is enemy esp (there is no teams its a ffa)

How can I make it so:

  • it will automatically update every time a player is added to workspace
  • make everyone but localplayer have the outline
-- R6
local Players = game:GetService("Players")

local function onPlayerAdded(player)
	local head = game.Workspace.player.Name.Head
	local headESP = Instance.new("Highlight")
	headESP.Name = "esp"
	headESP.Parent = head
end

for _, player in pairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

image
When I try doing player.Name it says it isn’t a valid member of Workspace

You can accomplish this by using the event when a character is added.

local Players = game:GetService("Players")

local function characterAdded(character)
	local head = character:WaitForChild("Head")
	local headESP = Instance.new("Highlight")
	
	headESP.Name = "esp"
	headESP.Parent = head
end

local function playerAdded(player)
	if player.Character ~= nil then
		characterAdded(player.Character)
	end
	
	player.CharacterAdded:Connect(characterAdded)
end

for _, player in ipairs(Players:GetPlayers()) do
	if player ~= Players.LocalPlayer then
		playerAdded(player)
	end
end

Players.PlayerAdded:Connect(playerAdded)

local head = game.Workspace:FindFirstChild(player.Name).Head

That’s not how that works. This is looking in the workspace for something called player then in that object looking for something called Name then in that object looking for something called Head

What you want to do is:
local head = game.Workspace[player.Name].Head

Almost, but not quite. Try this:

-- R6
local Players = game:GetService("Players")

local function onPlayerAdded(player)
    local character = player.Character or player
CharacterAdded:Wait()
	local head = character:WaitForChild("Head")
	local headESP = Instance.new("Highlight")
	headESP.Name = "esp"
	headESP.Parent = head
end

for _, player in pairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end

Players.PlayerAdded:Connect(onPlayerAdded)

Tell me if it works, or if it has any errors. This fix is closest to your own code, and probably the easiest to understand.

1 Like
local Game = game
local Players = Game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local function OnPlayerAdded(Player)
	local function OnCharacterAdded(Character)
		if Player == LocalPlayer then return end
		local Highlight = Instance.new("Highlight")
		Highlight.Adornee = Character
		Highlight.Parent = Character
	end
	
	local Character = Player.Character or Player.CharacterAdded:Wait()
	OnCharacterAdded(Character)
end

Players.PlayerAdded:Connect(OnPlayerAdded)
for _, Player in ipairs(Players:GetPlayers()) do
	OnPlayerAdded(Player)
end

Place inside StarterPlayerScripts.