Ad
Log in to vote
0

Why is HumanoidRootPart attempt index nil?

Asked by 15 days ago

i've been using bodyGyro to point my Tower to Enemy using HumanoidRootPart but it index nil. it was working before bodyGyro so I'm guessing it's something in the bodyGyro part. I can't seem to find where the error originated. The Debugger said the error is in the "local distance = (target.HumanoidRootPart.Position - newTower.HumanoidRootPart.Position).Magnitude" part

~~~~~~~~~~~~~~~~~

function FindNearestTarget(newTower) local maxDistance = 5 local nearestTarget = nil

for i, target in ipairs(workspace.Mobs:GetChildren()) do
    local distance = (target.HumanoidRootPart.Position - newTower.HumanoidRootPart.Position).Magnitude
    if distance < maxDistance then
        nearestTarget = target
        maxDistance = distance
    end
end

return nearestTarget

end

function tower.Attack(newTower) local target = FindNearestTarget(newTower)

if target and target:FindFirstChild("Humanoid") and target.Humanoid.Health > 0 then
    animateTowerEvent:FireAllClients(newTower, "Attack")

    local targetCFrame = CFrame.lookAt(newTower.HumanoidRootPart.Position, target.HumanoidRootPart.Position)
    newTower.HumanoidRootPart.BodyGyro.CFrame = targetCFrame

    target.Humanoid:TakeDamage(25)
end

task.wait(1)


tower.Attack(newTower)

end

function tower.Spawn(player, name, cframe) local towerExists = ReplicatedStorage.Towers:FindFirstChild(name)

if towerExists then
    local newTower = towerExists:Clone()
    newTower.HumanoidRootPart.CFrame = cframe
    newTower.Parent = workspace
    newTower.HumanoidRootPart:SetNetworkOwner(nil)

    local bodyGyro = Instance.new("BodyGyro")
    bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge)
    bodyGyro.D = 0
    bodyGyro.CFrame = newTower.HumanoidRootPart.CFrame
    bodyGyro.Parent = newTower.HumanoidRootPart

    for i, object in ipairs(newTower:GetDescendants()) do
        if object:IsA("BasePart") then
            PhysicsService:SetPartCollisionGroup(object, "Tower")
        end
    end

    coroutine.wrap(tower.Attack())(newTower)
else
    warn("Resquested Tower does not exist:", name)
end

end

return tower

~~~~~~~~~~~~~~~~~

1 answer

Log in to vote
0
Answered by 14 days ago

Try changing:

local distance = (target.HumanoidRootPart.Position - newTower.HumanoidRootPart.Position).Magnitude

to this:

local distance = (target:WaitForChild("HumanoidRootPart").Position - newTower:WaitForChild("HumanoidRootPart").Position).Magnitude

If this works, PLEASE mark this answer as accepted :)

Ad

Answer this question