Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
wookey12 174
6 years ago
Edited 6 years ago

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

Log in to vote
0
Answered by
UgOsMiLy 1074 Moderation Voter
6 years ago
Edited 6 years ago

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)
0
you could do character added Vulkarin 581 — 6y
0
Good idea; I've edited it now. UgOsMiLy 1074 — 6y
Ad
Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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

Answer this question