Attempt to index nil with FindFirstChildOfClass

the title says it all, i can’t seem to find a solution online or here on dev forms so i made my own topic, can somebody tell me what’s going on?

local Players = game:GetService("Players");
local totalDamage = 50;
local damageReduce = 1 -- How much you want to reduce the total damage from the player (based on how far the player is from the explosion)
local maxRange = 15
local Bomb = script.Parent.Detector

function getNpcsInRange(position, range)
	local npcs = game.Workspace:GetDescendants();
	local foundNpcs = {};

	for num, npcs in pairs(npcs) do
		local character = npcs:FindFirstChildOfClass("Humanoid")

		if character then
			if not Players:GetPlayerFromCharacter(character) then
			local torso = character.Parent:FindFirstChild("Torso") or character.Parent:FindFirstChild("LowerTorso");
			if torso then
				local distance = (torso.Position - position).magnitude
				if distance <= range then
					table.insert(foundNpcs, { npcs=npcs, distance=distance})
				end
			end
			end
			end
	end
	return foundNpcs;
end

function damageNpcs(position)
	local results = getNpcsInRange(position, maxRange)  
	print(#results) 

	for _, result in pairs(results) do
		local npc, distance = result.npc, result.distance;
		local npcDamage = (totalDamage - (distance * damageReduce))

		local humanoid = npc:FindFirstChildOfClass("Humanoid") --MAIN ERROR
		print(humanoid)
		humanoid:TakeDamage(npcDamage); 

		print("Dealt", npcDamage, "damage to", npc.Name)
	end
end

wait(10)
damageNpcs(Bomb.Position)

Well, I am unsure of the exact problem but I do feel like fixing a few things could help.
If the variable npc is returning “Attempt to index nil with FindFirstChildOfClass,” I’m pretty confident in saying that means that npc is nil. This would mean result.npc is nil too.

So, for starters, check what result.npc is getting.

1 Like

Maybe, try using FindFirstChild() or FindFirstChildWhichIsA()

You’re setting npc to result.npc instead of result.npcs.

2 Likes