Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

0

Plz Format the script better!

2 answers

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

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

This discussion is preserved as it was. New answers, comments, and votes are closed.