CharacterAdded not working

Hi,

I have the following code:

local localPlr = Players.LocalPlayer

localPlr.CharacterAdded:Connect(function(char: Model)
    localPlr:SetAttribute("IsAlive", true)
    print('Yessir')

    local humanoid = char:WaitForChild("Humanoid")
    humanoid.Died:Connect(function()
        localPlr:SetAttribute("IsAlive", false)
        localPlr:SetAttribute("InBuildMode", false)
        localPlr:SetAttribute("InPlaceMode", false)
        GuiServices.ShowHUD()
        GuiServices.HideGuiStandard()
    end)
end)

However upon spawning (not respawning, that works fine) the print statement “Yessir” is not being logged to the console. My guess is that the localscript may be running before the character initially spawns in, but when I add local stallScript = localPlr.CharacterAdded:Wait() before the CharacterAdded event, nothing changes.

Any clue as to why would be appreciated!

Since it works fine after respawning, I suspect that the code is running after the character has spawned. You can make a function called characterAdded(), connect it to the CharacterAdded() event and also call it if player’s character already exists.

local localPlr = Players.LocalPlayer

local function characterAdded(char: Model)
    localPlr:SetAttribute("IsAlive", true)
    print('Yessir')

    local humanoid = char:WaitForChild("Humanoid")
    humanoid.Died:Connect(function()
        localPlr:SetAttribute("IsAlive", false)
        localPlr:SetAttribute("InBuildMode", false)
        localPlr:SetAttribute("InPlaceMode", false)
        GuiServices.ShowHUD()
        GuiServices.HideGuiStandard()
    end)
end

if localPlr.Character then
    characterAdded(localPlr.Character)
end

localPlr.CharacterAdded:Connect(characterAdded)

That’s s because local scripts don’t detect PlayedAdded and CharacterAdded for the local player, what it is doing instead it’s listening to another player joining instead of yourself. What you can do it’s either put the script in starter character scripts or either make a server script and fire an event when a player joins.

This works! So my issue was that the initial character was spawning before the code ran, instead of my assumption of it running after.
You also replied (and sorta solved) an issue I had a few days ago haha, I appreciate your help :handshake:

1 Like

Players.LocalPlayer still returns a Player object much the same as referencing a Player object on the server, so the CharacterAdded method can still be used.

Oh yeah, my mistake, I thought you were using PlayerAdded, glad you fixed it :pray:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.