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

How do I fix Humanoid is not a valid member of "Model"?

Asked by 1 year ago

Hi, I'm trying to make walking npcs fight enemy npcs, this was successful however there's a bug where if the enemy is already dead by the time the ally npc detects the enemy, it will freeze and be unable to do anything. How can I fix this?

I tried adding so it would detect if the humanoid WAS nil beforehand however I still encounter this problem.

local Enemies = workspace.Enemies
local Humanoid = script.Parent:WaitForChild("Humanoid")
local Self = script.Parent
local AttackEffect = script.Parent.HumanoidRootPart.ParticleEmitter

local target = nil

function FindTarget()
    local maxdistance = 100
    local nearesttarget = nil

    for i, target in ipairs(Enemies:GetChildren()) do
        local distance = (target.HumanoidRootPart.Position - Self.HumanoidRootPart.Position).Magnitude
        --print(target.Name, distance)
        if distance < maxdistance then
            print(target.Name, "shall be initiated!")
            nearesttarget = target
        end

        return nearesttarget
    end
end


while true do
    local target = FindTarget()
    if target and target.Humanoid ~= nil then
        Humanoid:MoveTo(target.HumanoidRootPart.Position)
        Humanoid.MoveToFinished:Wait()
        if target.Humanoid == nil then return end
            if target.Humanoid.Health > 0 then
                target.Humanoid:TakeDamage(1)
                AttackEffect.Enabled = true
                print(target.Humanoid.Health)
            end
    end
    task.wait(.2)
    AttackEffect.Enabled = false
    end

The way it works is that it detects an enemy within it's range then pursue the enemy and damage them.

0
Use target:FindFirstChildOfClass("Humanoid") T3_MasterGamer 2189 — 1y
0
Thanks, this worked :D Dragonboy99711 5 — 1y

Answer this question