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

attempt to index nil with 'HumanoidRootPart' i get this error when i place a tower in my game, help?

Asked by 1 year ago
Edited 1 year ago

i am working on a tower defense game and when i place the tower it give me the error ServerScriptService.Main.Tower:52: ServerScriptService.Main.Tower:15: attempt to index nil with 'HumanoidRootPart'

here is the code

local PhysicsService = game:GetService("PhysicsService") local ServerStorage = game:GetService("ServerStorage") local ReplicatedStorage = game:GetService("ReplicatedStorage")

local events = ReplicatedStorage:WaitForChild("Events") local spawnTowerEvent = events:WaitForChild("SpawnTower")

local tower = {}

function FindNearestTarget(newTower) local maxDistance = 20 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() if target then target.Humanoid:TakeDamage(10) end

task.wait(0.7)

tower.Attack(newTower)

end

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

if towerExist then

    local newTower = towerExist:Clone()
    newTower.HumanoidRootPart.CFrame = cframe
    newTower.Parent = workspace.Towers
    newTower.HumanoidRootPart:SetNetworkOwner(nil)

    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("The Tower Is A Ghost?!", name)
end

end

spawnTowerEvent.OnServerEvent:Connect(tower.Spawn)

return tower

0
Plz Format the script better! MattVSNNL 620 — 1y

2 answers

Log in to vote
1
Answered by
bbissell 346 Moderation Voter
1 year ago

Your function FindNearestTarget requires a parameter (newTower)

function FindNearestTarget(newTower) 

When you call the function, it does not have a parameter:

function tower.Attack(newTower) local target = FindNearestTarget() if target then target.Humanoid:TakeDamage(10) end

So that should be

function tower.Attack(newTower) local target = FindNearestTarget(newTower) if target then target.Humanoid:TakeDamage(10) end
Ad
Log in to vote
0
Answered by
enes223 327 Moderation Voter
1 year ago

hey you! have you ever heard of enes? if you are in trouble, better call enes!

Answer this question