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

Workspace.Rifle Dummy.Script:46: attempt to index nil with 'Health'?

Asked by 2 years ago
Edited 2 years ago

Hello, I need help on a Dummy NPC I'm trying to make. If there's no target in sight or the target went out of range, it would break and create a error saying: attempt to index nil with 'Health'

This was not supposed to happen because of the way I coded it, here is the code (There is only server-side code, no client code.

local Humanoid = script.Parent.Humanoid
local HumanoidRootPartDummy = script.Parent.HumanoidRootPart
local Animator = Humanoid.Animator
local Loads = {
    Fire = Animator:LoadAnimation(script.Parent.Fire),
    Idle = Animator:LoadAnimation(script.Parent.Idle)
}
local dmg = 7
local range = 79

function findTarget()   
    for i, child in pairs(workspace:GetChildren()) do
        if child:IsA("Model") and child:FindFirstChild("Humanoid") and child:FindFirstChild("HumanoidRootPart") and child ~= script.Parent then
            local HumanoidRootPart = child:FindFirstChild("HumanoidRootPart")
            local HumanoidTarg = child:FindFirstChild("Humanoid")
            local pos = (HumanoidRootPartDummy.Position - HumanoidRootPart.Position).Magnitude
            if pos < range and HumanoidRootPart and HumanoidTarg then
                return HumanoidRootPart, HumanoidTarg
            end
        end
    end 
end

function bulletGeneration(TargetRootPart)
    local Trail = Instance.new("Beam")

    local Attachment1 = Instance.new("Attachment")
    local Attachment2 = Instance.new("Attachment")

    Attachment1.Parent = HumanoidRootPartDummy
    Attachment2.Parent = TargetRootPart
    Trail.Attachment0 = Attachment1
    Trail.Attachment1 = Attachment2
    Trail.Enabled = true
    Trail.Color = ColorSequence.new{
        ColorSequenceKeypoint.new(0, Color3.new(1, 1, 1)),
        ColorSequenceKeypoint.new(0.5, Color3.new(1, 0.721569, 0.270588)),
        ColorSequenceKeypoint.new(1, Color3.new(1, 0.933333, 0))
    }
    wait(Loads.Fire.Length / 12)
    Trail:Destroy()
end

while wait() do
    local root, targhum = findTarget()
    if targhum.Health ~= 0 and root and targhum then
        Loads.Fire:Play()
        targhum:TakeDamage(dmg)
        script.Parent.HumanoidRootPart.CFrame = CFrame.lookAt(script.Parent.HumanoidRootPart.Position, root.Position)
        wait(Loads.Fire.Length)
    else
        Loads.Fire:Stop()
        Loads.Idle:Play()
        Loads.Idle.DidLoop:Wait()
    end
end

If you read this all, good job!

I tried almost everything I could, I always miss something that I somehow didn't notice so simple. But I really can't figure this one out.

Also, the BulletGeneration function isn't doing anything visual.

I stopped scripting for like 1 in a half months, so I'm a little rusty.

0
Said BulletRegeneration instead of BulletGeneration, oopsie! Finty_james 269 — 2y

Answer this question