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

Why is my CharacterAdded/PlayerAdded code not working properly?

Asked by 2 years ago

So I wanted to make a script where when a player joins, if the player has a specific UserId, they will spawn with a specific custom character. The script works perfectly fine when a player first joins the game, but when the player kills their character, the script starts loop spawning the player's character. Can anyone help see if my code has any problem that results in this loop?

local Tetrantyl = game:GetService("ReplicatedStorage"):FindFirstChild("TetraMorph")

function PlayerAdded(player)
    if player.UserId == 161506000 then
        print("Tetrantyl has spawned.")
    end
    local function CharacterAdded(Character)
        if player.UserId == 161506000 then
            local PlayerAvatar = Tetrantyl:Clone()
            PlayerAvatar.Name = "StarterCharacter"
            PlayerAvatar.Parent = game:GetService("StarterPlayer")
            wait(.1)
            player:LoadCharacter()

        end

    end
    CharacterAdded(player.Character or player.CharacterAdded:wait())
    player.CharacterAdded:Connect(CharacterAdded)
end

game.Players.PlayerAdded:Connect(PlayerAdded)

for _,player in pairs(game.Players:GetPlayers())do
    spawn(function() PlayerAdded(player) end)
end

1 answer

Log in to vote
0
Answered by
pwx 1581 Moderation Voter
2 years ago

That's because you've put the UserId check outside of the actual check of the loop, therefore for each player that joins is how many times it would loop.

Here's a simple fix:

local Players = game:GetService('Players')

function onPlayerAdded(Player)
    local function onCharacterAdded(Character)
        local PlayerAvatar = Tetrantyl:Clone()
                PlayerAvatar.Name = "StarterCharacter"
                PlayerAvatar.Parent = game:GetService("StarterPlayer")
                wait(.1)
                player:LoadCharacter()
    end -- onCharacterAdded
    if Player.UserId == 161506000 then
        Player.CharacterAdded:Connect(onCharacterAdded)
    end -- userId check
end -- playerAdded

Players.PlayerAdded:Connect(onPlayerAdded)

Another problem you may wanna know of when you use StarterCharacter in StarterPlayer in a Server script, this will eventually morph everyone into said character on a respawn since StarterPlayer is used for each player globally.

Ad

Answer this question