How do I fix this "attempt to index nil with FindFirstChildOfClass" error?

I’m trying to make a stick weapon that ignores all players but still hurts NPC zombies in my game, however I keep getting this error and no damage or knockback is dealt when I attempt to hit the zombie with my weapon.


This is my code that I made to carry out damage and knockback as well as checking if the hit.Parent is a player or not
local allyTeam = game:GetService("Teams")["Humans"] function OnTouch(hit) print(hit.Name) local target = game.Players:GetPlayerFromCharacter(hit.Parent) local Humanoid = target:FindFirstChildOfClass("Humanoid") --- this line here is the problem if Humanoid and target.TeamColor ~= allyTeam.TeamColor then target:TakeDamage(25) local Root = hit.Parent.HumanoidRootPart local velocity = Instance.new("BodyVelocity") velocity.MaxForce = Vector3.new(10000,10000,10000) velocity.Velocity = (Stickv2.Parent.HumanoidRootPart.CFrame.LookVector+Vector3.new(0,1,0)) * 50 velocity.Parent = Root wait(0.25) velocity:Destroy() if not Humanoid or target or target.TeamColor == allyTeam.TeamColor then return end end end
I tried researching this error and believe it is because the game is trying to call something that isn’t loaded in yet, but I’m not really sure how to properly add a wait for this specific issue. Any help would be greatly appreciated!

(Edit): Sorry if the code formatting is weird I’m not really sure why it displays like that or how to fix it since it looks different in the text editor.

this would error when hit isn’t a player’s character’s limb because :GetPlayerFromCharacter(hit.Parent) would give you nil, then you’re attempting to do nil:FindFirstChildOfClass("Humanoid")

also, humanoid is in the character, not player, so it wouldnt work even if hit was a player’s character’s limb

1 Like