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

Why is my CharacterAdded/PlayerAdded code not working properly?

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

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.

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