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

Why does my script index a nil value from Humanoid.Health?

Asked by 4 years ago
local Humanoid = script.Parent:FindFirstChild("Humanoid")

function findHostile()
    local hostile = Humanoid:FindFirstChild("creator")
    if hostile ~= nil then
        if hostile.Value ~= nil then
            local hostileHumanoid = hostile.Value:FindFirstChild("Humanoid")
            while hostileHumanoid.Health >= 0 do
                Humanoid:MoveTo(hostile.Position,hostile)
            end
        end
    end
end

Humanoid.HealthChanged:Connect(findHostile)

It said that 'while hostileHumanoid.Health >= 0 do' tried to index a nil value with Health. Could anyone help me? This is a script under an NPC, and I'm trying to make it so that once you damage it, it follows you instantly.

3 answers

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

Normally the Value of creator is a UserData (Instance). So you need to find the Character.

local Humanoid = script.Parent:WaitForChild("Humanoid")

Humanoid.HealthChanged:Connect(function()
    local creator = Humanoid:WaitForChild("creator")
    if creator ~= nil then
        local hostile = creator.Value
        print(hostile.Name, type(hostile), typeof(hostile))
        if hostile ~= nil and hostile.Character then
            local hosCharacter = hostile.Character
            local hosHumanoid = hosCharacter:WaitForChild("Humanoid")
            local hosHPart = hosCharacter:WaitForChild("HumanoidRootPart")
            repeat wait()
                Humanoid:MoveTo(hosHPart.Position, hosHPart)
            until hosHumanoid.Health >= 0 or hosCharacter == nil
        end
    end
end)
0
Thanks! CrypxticDoge 135 — 4y
Ad
Log in to vote
1
Answered by 4 years ago

Try changing

while hostileHumanoid.Health >= 0 do

to

while hostileHumanoid and hostileHumanoid.Health >= 0 do

Since you do :FindFirstChild'Humanoid' you need to check if it didnt return nil first.

0
Sorry doesnt work CrypxticDoge 135 — 4y
0
It seems hostileHumanoid is nil itself CrypxticDoge 135 — 4y
Log in to vote
0
Answered by
qVoided 221 Moderation Voter
4 years ago

I'm assuming that 'hostile' is an ObjectValue.

Try this:

local Humanoid = script.Parent:FindFirstChild("Humanoid")

function findHostile()
    local hostile = Humanoid:FindFirstChild("creator")
    if hostile ~= nil then
        if hostile.Value ~= nil then
            local hostileHumanoid = hostile.Value
            while hostileHumanoid.Health >= 0 do
                Humanoid:MoveTo(hostile.Position,hostile)
            end
        end
    end
end

Humanoid.HealthChanged:Connect(findHostile)
1
Remeber that health is not a child of a Player CrypxticDoge 135 — 4y
0
Im gonna edit this, wait qVoided 221 — 4y
0
What is the hostileHumanoid's value? qVoided 221 — 4y
0
its supposed to be the humanoid of the player that attacked the NPC CrypxticDoge 135 — 4y

Answer this question