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

Attempt to index nil with 'Position'?

Asked by
naturedat 124
4 years ago
Edited 4 years ago

I'm basically just making an enemy npc that goes to the nearest npc in the game and attack each other. This script is located in the npc. The error is in line 29. Help please:

01local dis = math.huge
02local rot = script.Parent.HumanoidRootPart.Position
03local animation = script:WaitForChild("Animation")
04local hold = script:WaitForChild("Hold")
05local human = script.Parent:WaitForChild("Humanoid")
06local ani = human:LoadAnimation(animation)
07local anima3 = human:LoadAnimation(hold)
08anima3:Play()
09ani:Play()
10 
11function findNearestHumanoid(pos)
12    local list = game.Workspace:GetChildren()
13    for i = 1,#list do
14        local v = list[i]
15        if v.ClassName == "Model" and v ~= script.Parent then
View all 41 lines...

Thank you!

1 answer

Log in to vote
2
Answered by
Necro_las 412 Moderation Voter
4 years ago
Edited 4 years ago

Your function findNearestHumanoid() can return nil if there is no one near, and then you cant get nil.Position. I recomend creating a variable to check its presence, like:

1local nearestHumanoid = findNearestHumanoid(rot)
2local map
3if nearestHumanoid then
4    map = nearestHumanoid.Position - rot
5end
0
Thanks, I actually found out why the function returned nil, it was because on line 18, humanoid.Health <= 0 so it was a stupid mistake but thanks! naturedat 124 — 4y
Ad

Answer this question