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

1 comment
Plz Format the script better!