Why doesn't my code work?

Hey recently i’ve been working on a dash system with a trail but i’ve been getting “attempt to index nil with PrimaryPart” error and idk why.

here’s the code

game.Players.PlayerAdded:Connect(function(plr)
	local character = plr.Character
	local root = character.PrimaryPart
	local attachment = Instance.new('Attachment')
	attachment.Name = "1"
	attachment.Parent = root
	
	local attachment2 = attachment:Clone()
	attachment2.Name = "2"
	attachment2.Parent = root
	
	local trail = Instance.new('Trail')
	trail.Name = "trail"
	trail.Enabled = false
	trail.Parent =  root
	trail.Attachment0 = attachment
	trail.Attachment1 = attachment2
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local character = plr.Character
	if character then
		for _,v in pairs(character:GetChildren()) do 
			if v.Name == "trail" then 
				v:Destroy()
			end 
		end 
	end 
end)

When the player gets added, their character may load a bit after, causing player.Character to be nil and giving the error that character doesn’t exist. If the character doesn’t exist then, you can use local character = plr.Character or plr.CharacterAdded:Wait(), which waits for the character to load.

Not related to the error but when the player leaves, you don’t need to remove the trails from the character as it is destroyed on leave

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