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

attempt to index nil with 'FindFirstChild': how to fix it??I can't fix it. I tried many ways.

Asked by 3 years ago
Edited 3 years ago

Hi! i can't make an teleport to an building from a part (part is position where the teleport target)

code:


for i = 1,#elevatorlobbyplayers do local char2 = game.Workspace:FindFirstChild(elevatorlobbyplayers) local HMR3 = char2:FindFirstChild("HumanoidRootPart") if HMR3 then HMR3.CFrame = CFrame.new(elevator.TeleportPart.Position) end end

the code is piece of code where the error

EDIT: i alerady fixed it by adding into players a tag and detecting it

0
Which line is giving the error AntoninFearless 622 — 3y
0
When finding the HMR3 TemaTechYT 2 — 3y
0
At line 3 TemaTechYT 2 — 3y
0
Char2 is nil. JesseSong 3916 — 3y

1 answer

Log in to vote
0
Answered by
Elyzzia 1294 Moderation Voter
3 years ago
Edited 3 years ago

you're passing elevatorlobbyplayers as an argument to FindFirstChild, not a player's name

assuming that elevatorlobbyplayers is an array of player names, you can do this instead

local Players = game:GetService("Players") -- always use GetService to..get services
-- it's a commonly adopted practice, it ensures that your code doesn't error, and it's sliiiiiiightly more efficient than directly referencing the service every time
-- also it just makes your code look a bit cleaner imo

for i = 1, #elevatorlobbyplayers do
    -- you should NEVER EVER EVER use workspace:FindFirstChild() to get player characters, since players could have the same name as something else in the workspace
    local char2 = Players:FindFirstChild(elevatorlobbyplayers[i]).Character -- notice the [i] after elevatorlobbyplayers
    local HMR3 = char2:FindFirstChild("HumanoidRootPart")
    if HMR3 then
        HMR3.CFrame = CFrame.new(elevator.TeleportPart.Position)
    end
end

also, this isn't necessary, but a pairs (or ipairs) loop is a slightly cleaner alternative to a numeric for loop in this scenario

-- _ is usually used as a placeholder variable for when you don't actually need a value
-- in this case, that value would be the index that playerName is at
for _, playerName in pairs(elevatorlobbyplayers) do
    local char2 = Players:FindFirstChild(playerName).Character
    local HMR3 = char2:FindFirstChild("HumanoidRootPart")
    if HMR3 then
        HMR3.CFrame = CFrame.new(elevator.TeleportPart.Position)
    end
end
0
still not working lol TemaTechYT 2 — 3y
Ad

Answer this question