Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

adding teammate GUI markers in local script- best way to loop through players?

Hopefully a simple issue- I have an image label under a billboard GUI that I'm trying to assign to each player in the server who is a teammate of the local player. I have the following in a local script under starterGUI, because each player will see diff things depending on their team combination. This is probably simple, but I'm not sure the proper way to loop through every player from a localscript. I've tried multiple methods and it seems inconsistent whether it captures every player in the game depending on the join order. What is the most reliable way from a localscript to ensure i can loop through all possible teammates for local player? (that exist currently as well as those that may be added later)

local players = game:GetService("Players")
local locPlayer = game:GetService("Players").LocalPlayer
local markerGui = script.Parent

players.PlayerAdded:Connect(function()
	--each time a player is added
	--// Loop through all existing players
	for _, player in ipairs(players:GetPlayers()) do
		if player.Character and player.Character:FindFirstChild("Humanoid") and player.character ~= locPlayer.character and player.Team == locPlayer.Team then
				local clonedgui = markerGui:Clone()
				clonedgui.ImageLabel.ImageColor3 = player.TeamColor.Color
				clonedgui.Parent = game.Workspace:WaitForChild(player.Name).Head 
		end
	end
end)

Appreciate any advice!

1 answer

So I believe I solved this though I don't know that its the "best" method, but I just needed to add a separate function to fill in the missing players that were not caught by the playeradded function.

local Players = game:GetService("Players")
	for i, player in pairs(Players:GetPlayers()) do
		local character = player.Character or player.CharacterAdded:Wait()
		blah blah blah

the combo of both of these in local script seems to cover it

game.Players.PlayerAdded:Connect(function(p2)
	p2.CharacterAdded:Connect(function(character)
		blah blah blah

im sure i could clean up my code but its working now to display markers only for teammates :)

This discussion is preserved as it was. New answers, comments, and votes are closed.