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

why is my for in pairs loop not changing the head color?

i just want to simply change the color of everyone's head to blue. why is it not working? there is no error either. not filtering enabled.

local players = game.Players:GetPlayers()
game.Players.PlayerAdded:connect(function()
	wait(3)
for i,Torso in pairs(players) do
	Torso.Character["Body Colors"].HeadColor.Color3 = Color3.fromRGB(13, 105, 172)
end
end)

2 answers

✓ Accepted answer

The first line will return an empty array, as the script is run at the beginning of the game, therefore any player that joins after will not be counted.

Use this instead

game.Players.PlayerAdded:Connect(function(player) -- connect is deprecated, use Connect. And player is the player that joined (the object in Players, not in the workspace).
	player.CharacterAdded:Wait()
	wait(3) -- if this isn't needed any more, remove it.
	for _,Torso in pairs(game.Players:GetPlayers()) do
		if Torso and Torso.Character and Torso.Character:FindFirstChild("Body Colors") then
			Torso.Character["Body Colors"].HeadColor3 = Color3.fromRGB(13, 105, 172)
		end
	end
end)

2 comments

0

you could do character added

0

Good idea; I've edited it now.

I re-wrote your code a bit and gave you a couple options on how you want the timing to work when changing the characters' head colors. It's probably a bit overkill for what you're doing, but it just shows how many different ways you can approach a simple problem (Of course, you could always just fix your for loop and call it a day :p)

local desiredColor = Color3.fromRGB(13, 105, 172)

-- This function will change the color of the character passed to it
local function setCharacterHeadColor(character)
    local head = character:WaitForChild("Head", 5)
    if head then
        head.Color = desiredColor
    end
end

-- This function will set all the characters' head colors once
local function setAllCharacterHeadColors()
    for _, player in pairs(game.Players:GetPlayers()) do
        spawn(function()
            while not player.Character do wait() end
            setCharacterHeadColor(player.Character)
        end)
    end
end

--[[
    You don't need both of the below, so pick the one that works for you and
    delete the other one.
]]--

-- These connections will set the head color every time a character spawns
game.Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(setCharacterHeadColor)
end)

-- This loop will set all the characters' head colors every 10 seconds
while wait(10) do
    setAllCharacterHeadColors()
end

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