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

Why won't the player stay anchored when they join?

Asked by 8 years ago

I need a player's torso to be anchored when they join the server. I made a script to do this, but it doesn't work. I get an error saying that 'Character' is a nil value. What did I do wrong?

game.Players.PlayerAdded:connect(function(newPlayer)
    newPlayer.Character.Torso.Anchored = true
end)

1 answer

Log in to vote
2
Answered by 8 years ago

In ROBLOX, the player loads before the character. With this knowledge, you need a way to wait until the character is available before anchoring their torso.. There are two methods I recommend for you to use and they vary depending on what you want to do.

For each of my methods, you may need to use WaitForChild. WaitForChild essentially waits until the child specified is available. This causes less errors but if the child is never added in, the script will yield (wait) forever, not returning an error and causing confusion when debugging your code.

Method 1:

If you want the script to only work when the player first joins the server, you can use the CharacterAdded event and the wait function of an event. The wait function is similar to wait(), but instead of waiting for a certain amount of time before continuing on with the rest of the code, it waits until the event you called it on has fired.

If you chose the first method, your script should look like this:

game.Players.PlayerAdded:connect(function(newPlayer)
    newPlayer.CharacterAdded:wait() --Waits until the CharacterAdded event fires before continuing with the rest of your code.
    newPlayer.Character:WaitForChild("Torso").Anchored = true --Waits for the torso to become available, then anchors it.
end)

Method 2:

If you want the script to work each time the player spawns in, you need to make another function similar to line 1 which use newPlayer.CharacterAdded instead of game.Players.PlayerAdded. You will need another end with a parenthesis around it if you choose to do this.

If you chose the second method, your script should look like this:

game.Players.PlayerAdded:connect(function(newPlayer)
    newPlayer.CharacterAdded:connect(function(char) --You can just use the char variable instead of player.Character as the variable points directly to the player's character already.
        char:WaitForChild("Torso").Anchored = true --See how this line is shorter than the other line on the first method because we used the char variable?
    end)
end)

I hope my answer helped you. If it did, be sure to accept it.

Ad

Answer this question