Still have questions? Join our Discord server and get real time help.
0

Why does my output say "Attempt to index nil with "Position"?

I've been trying to fix this issue, but cannot seem to find a fix. Here is the code below:

local Player = game.Players.LocalPlayer:FindFirstChild("Humanoid")
local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")

local Door = game.Workspace.DualDoorsE.SecondaryDoorE2
local DoorPrimaryPart = Door.PrimaryDoorPart

local NearDoor = false

RunService.RenderStepped:Connect(function()
if (Player.Position - DoorPrimaryPart.Position).magnitude < 5 then
NearDoor = true
DoorPrimaryPart.EToOpen.Enabled = true
else
NearDoor = false
DoorPrimaryPart.EToOpen.Enabled = false
end
end)

UIS.InputBegan:Connect(function(Input)
if Input.UserInputType == Enum.UserInputType.Keyboard then
local Key = Input.KeyCode
if Key == Enum.KeyCode.E and NearDoor == true then
Door.ToggleDoor:FireServer()
end
end
end)


According to the output, this is the line that triggers the error:

if (Player.Position - DoorPrimaryPart.Position).magnitude < 5 then


Can someone figure out why that occurs? I would really appreciate the help.

0
Edited 8 days ago

The humanoid is in the character not the player, to access the character use:

player.Character


Then, once you have that, you need to change .magnitude to .Magnitude , i am not sure if that changes anything but i would suggest doing it. Also, use the HRP's position as it is more reliable. Fixed code:

local Player = game.Players.LocalPlayer
local Character = Player.Character -- Character is the character
local hum = Character:FindFirstChild("Humanoid") -- hum is the humanoid
local HRP = Character.HumanoidRootPart -- HRP is the humanoidrootpart
local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")

local Door = game.Workspace.DualDoorsE.SecondaryDoorE2
local DoorPrimaryPart = Door.PrimaryDoorPart

local NearDoor = false

RunService.RenderStepped:Connect(function()
if (HRP.Position - DoorPrimaryPart.Position).Magnitude < 5 then -- HRP instead of Player or Character
NearDoor = true
DoorPrimaryPart.EToOpen.Enabled = true
else
NearDoor = false
DoorPrimaryPart.EToOpen.Enabled = false
end
end)

UIS.InputBegan:Connect(function(Input)
if Input.UserInputType == Enum.UserInputType.Keyboard then
local Key = Input.KeyCode
if Key == Enum.KeyCode.E and NearDoor == true then
Door.ToggleDoor:FireServer()
end
end
end)

0
On Line 6, you forgot to close the bracket. Dovydas1118 993 — 9d