Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

"attempt to index field 'PrimaryPart' (a nil value)" ?

Hello everyone ! I can't figure out why I have this error in my script and how do I fix it?

My error: "attempt to index field 'PrimaryPart' (a nil value)" at the line 17

My code:

local run = game:GetService("RunService")
local teams = game:GetService("Teams")
local tS = game:GetService("TweenService")
local player = game.Players.LocalPlayer
local character = player.Character
local world = workspace:WaitForChild("PrisonZone")
local RemoteEvent = game.ReplicatedStorage.Events.event
local criminalGUI = game.StarterGui.Criminal

player.CharacterAdded:connect(function(c)
	character = c
end)
local heartbeat = run.Heartbeat

local zoneTrackingService = heartbeat:Connect(function()
	if player.Team == teams.Prisonnier and character then
		local offset = world.CFrame:pointToObjectSpace(character.PrimaryPart.Position)
		local halfSize = world.Size/2
		if offset.x<-halfSize.x or offset.x>halfSize.x or offset.z<-halfSize.z or offset.z>halfSize.z then
			RemoteEvent:FireServer({reason="changeTeam"; team=teams.Criminal})
		end
	end
end)

Can you help me? Thank you in advance

1 answer

The character probably isn't fully loaded by the time your heatbeat loop starts. Try adding these lines between lines 5 and 6 and see if it helps:

if not character or not character.Parent then
	character = player.CharacterAdded:wait()
end

This discussion is preserved as it was. New answers, comments, and votes are closed.