Character's PrimaryPart attempt to index nil with 'Position'

I’m attempting to compare both the character’s primarypart and a part, but it doesn’t seem to like that and gives me a straight error. I tried with other parts, but apparently they weren’t in the model, when they were. What’s the concurrent issue here? Here’s the code:

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local safezone = game.Workspace:WaitForChild("Safezone")
local distance = (char.PrimaryPart.Position - safezone.Position).Magnitude

I’ve received this error: “Humanoid is not a valid member of Model”

that means you are referencing the character wrong, its saying that the character is nil i think

I tried doing :WaitForChild(“Humanoid”) and it functions normally, that’s surprising to see it referencing my character as nil.

To fix your problem you need to put distance inside of a loop.

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local safezone = game.Workspace:WaitForChild("Safezone")
while wait() do
	local distance = (safezone.Position - char.PrimaryPart.Position).Magnitude
	print(math.floor(distance)) -- To make number clear
end

If you put it outside the loop it will show the error.
Edit: You also need to update distance or else it will stuck in one number.

1 Like

This is due to the current ordering of the avatar events, which are very unintuitive and confusing even if you do know how they work. There was an announcement mentioning it’d be improved soon :tm:, but it’s been over a year with no mention of what happened to the update.

Relevant bit:

Current Ordering                            New Ordering
1.  Call LoadCharacter                          Call LoadCharacter 
2.  Player.Character is set                     Character appearance is initialized 
3.  CharacterAdded fires                        Character rig built/character scaled
4.  Player.Character changed event              Character is cframed to spawn location   
5.  Character appearance is initialized         Player.Character is set
6.  CharacterAppearanceLoaded fires             Player.Character changed event  
7.  Character parented to DataModel             Character parented to DataModel
8.  Character rig built/character scaled        CharacterAdded fires  
9.  Character is cframed to spawn location      CharacterAppearanceLoaded fires 
10. LoadCharacter returns                       LoadCharacter returns 

(Notice that CharacterAdded fires before character appearance is initialized.)

@ScriptOfTheSea: The only reason your’s works is because a while wait() do loop will call wait() before indexing the character’s PrimaryPart. This isn’t an actual fix, just a case where yielding a bit will sort everything out.

3 Likes