Code doesn't work

I’m sorry if I’m using this wrong.

I’m trying to make a quick little teleport feature (I don’t really care how bad it is). But for some reason when I play the game the output says that my “player” doesn’t have leaderstats in it (which it does btw).

game.Players.PlayerAdded:Connect(function(plr)
	if plr.leaderstats.Level.Value == 1 then
		plr.Character.HumanoidRootPart.CFrame = workspace.A.CFrame
	else
		if plr.leaderstats.Level.Value == 2 then
			plr.Character.HumanoidRootPart.CFrame = workspace.B.CFrame
		end
	end
end)

Add a local variable called Leaderstats, index it using WaitForChild() and use that variable rather than player.leaderstats.

1 Like

You can add WaitForChild, to check if leader stats and level actually exist as the player child at that moment.

game.Players.PlayerAdded:Connect(function(plr)

    local leaderstats = plr:WaitForChild("leaderstats")
    local Level = leaderstats:WaitForChild("Level")

	if Level Value == 1 then
		plr.Character.HumanoidRootPart.CFrame = workspace.A.CFrame
	else
		if Level.Value == 2 then
			plr.Character.HumanoidRootPart.CFrame = workspace.B.CFrame
		end
	end
end)
1 Like

It could be because the script runs slightly before leaderstats is created. I would instead create the leaderstats in the same script above the playeradded part

Put a CharacterAdded event inside the PlayerAdded one. Then the code will go inside the CharacterAdded event.

game.Players.PlayerAdded:Connect(function(plr)
    plr.CharacterAdded:Connect(function(Character)
         -- Code
    end)
end)
1 Like

That didn’t change anything. it only made it so I didn’t have to do plr.Character.

1 Like

Maybe try using WaitForChild on the HumanoidRootPart? Plus, The CharacterAdded event will fire everytime the Character gets added, So it has less chances of the Code not working due to the fact referencing the Character before it gets added may result in an error.

1 Like

I’m a little new to coding but it just says
ServerScriptService.Script:2: attempt to index nil with 'WaitForChild'.

1 Like

You need to use WaitForChild on the Character:

plr.Character:WaitForChild("HumanoidRootPart").Position = Vector3.new(X, Y, Z) -- Your position here instead
1 Like

Basically

1 Like