Attemp to index nil with primarypart of player's character

 game.Players.PlayerAdded:Connect(function(player)
       player.Character.PrimaryPart.CFrame = math.random(10,100)
end)

Whenever I run this it the error says
ServerScriptService.Script:3: attempt to index nil with ‘PrimaryPart’

And I dont understand how I am as I’m just getting the humanoidrootpart of the player’s character

1 Like

The character does not spawn instantly when the player joins. You can detect when the character spawns using Player.CharacterAdded (when this fires, the character hasn’t fully loaded yet, but I think the HumanoidRootPart will already exist).

Also, math.random() gives a number, not a CFrame. The CFrame constructed in the code below is probably not what you want but I’m not sure what you are trying to do.

local Players = game:GetService("Players")

local characterAddedConnections = {}

game.Players.PlayerAdded:Connect(function(player)
	characterAddedConnections[player] = player.CharacterAdded:Connect(function(character)
		character.PrimaryPart.CFrame = CFrame.new(math.random(10,100), math.random(10,100), math.random(10,100))
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	characterAddedConnections[player]:Disconnect()
	characterAddedConnections[player] = nil
end)

What is character added connections for ?

The characterAddedConnections table and the code in the end are used for avoiding memory leaks (avoiding data that is no longer needed staying in memory).

If I’ve understood correctly, connections (RBXScriptConnection objects) do not get garbage collected before they are disconnected. When an instance is destroyed, connections to its events are automatically disconnected. However, when a player leaves the game, the Player instance is not destroyed allthough it’s parented to nil. This means that the connections to the events of a Player instance are not automatically disconnected when the player leaves.

The table characterAddedConnections is for storing the connection until the player leaves so that it can be disconnected then (and it’s removed from the table after disconnecting it so that there are no references to it anymore).

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