Half the time the CharacterAdded code does not run?

Whenever I test play, it seems to be a 50% chance that the CharacterAdded code actually works. I’ve tried doing

repeat wait until workspace[Player.Name]
workspace:WaitForChild(Player.Name)

But that didn’t change anything; the code I’m doing is below and I’m using the DataStore2 module.

Players.PlayerAdded:Connect(function(Player)
	local InventoryData = DataStore2("Inventory5", Player)	
	InventoryData:Get(Default)
	
	Player.CharacterAdded:Connect(function(Character)
		workspace:WaitForChild(Player.Name)
		print(1)
		local Backpack = Backpacks[InventoryData:Get().Equipped.Backpack]:Clone()
		local Weld = Instance.new("Motor6D")
		Weld.Part0 = Backpack
		Weld.Part1 = Character.UpperTorso
		Weld.C0 = Information.Backpacks[InventoryData:Get().Equipped.Backpack].Weld
		Weld.Parent = Backpack
		Backpack.Parent = Character
	end)
end)

Put your CharacterAdded connection before the :Get call. :Get yields, which means the character could exist before you actually connect the CharacterAdded.

1 Like

Okay, thank you very much.

Do you recommend putting the default value whenever I use :Get() just in case?

If you really want to make this watertight regardless of code ordering, just extract the function you run on CharacterAdded as a named function instead of anonymous, and then also call that straight away when the Character is already defined on the player.

2 Likes

It wouldn’t hurt.