Hello! I have been trying to make a raycasting gun that checks if it hit a character or the character's held tools. So far I could not find anything about this.
My code:
if hit then if hit.Parent:FindFirstChild("Humanoid") or hit.Parent.Parent:FindFirstChild("Humanoid") or hit.Parent.Parent.Parent:FindFirstChild("Humanoid") then if hit.Parent.Humanoid.Health > 0 then hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 10 end end end
Why am I trying to see if it hit any of a character's tools?
I want the player to be able to shoot the other player ignoring if the slight part of another gun is blocking it.
How my Tool looks Image/Picture
Error(s)/Stacktrace
12:25:06.349 - ServerScriptService.ServerGun:21: attempt to index field 'Parent' (a nil value) 12:25:06.350 - Stack Begin 12:25:06.350 - Script 'ServerScriptService.ServerGun', Line 21 12:25:06.350 - Stack End
Answer/What I did to solve it: https://pastebin.com/raw/cd2RC2gy
try checking if it isnt nil (nil = nothing, nothingness.) check if something isnt nil by the code below:
if part then print("it exists!") end
alternatively:
if part ~= nil then print("it exists (too)!") end
if hit then if hit.Parent then local hum = hit.Parent:FindFirstChild("Humanoid") or hit.Parent.Parent:FindFirstChild("Humanoid") or hit.Parent.Parent.Parent:FindFirstChild("Humanoid") if hum then if hum.Health > 0 then hum.Health = hum.Health - 10 end end end end
hope that helped
Your code checks if the part hit is correct, but gets the wrong humanoid.
if (hit) then local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid") or hit.Parent.Parent:FindFirstChildOfClass("Humanoid") if (humanoid) then hit.Parent.Humanoid:TakeDamage(10) --we don't know if it's the second parent or not --which means it'll error if it hits a hat or tool end end
if (hit) then local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid") or hit.Parent.Parent:FindFirstChildOfClass("Humanoid") if (humanoid) and (humanoid.Health > 0) then humanoid:TakeDamage(10) --we know for sure the humanoid exists --which means errors aren't possible unless --hit's parent is nil end end
As you can see, the var humanoid
checks if the parent of the part is the character and looks for the humanoid. The or
is used to check the second parent (incase the raycast hits tools or hats).
Note: Humanoid:TakeDamage() will not damage the humanoid if they have a forcefield. Subtracting the health will damage unless their health is inf.