Touched event glitching when not hitting a player

So I have this Touched event that detects if it’s hitting a player or a regular material and only about 1/10th of a time it glitches and says this in the output:

13:00:55.235 - ServerScriptService.Script:905: attempt to index nil with 'Name'
13:00:55.236 - Stack Begin
13:00:55.236 - Script 'ServerScriptService.Script, Line 905 - function FakeRayGuns
13:00:55.237 - Script 'ServerScriptService.Script', Line 1919
13:00:55.237 - Stack End

“FakeRayGuns” is what I called my touched function because its meant to mimic Rays and it works fine usually but here is the script:

local DetectedHumanoid = nil

if Hit.Parent.Name ~= Player.Name and Hit.Parent:FindFirstChild("Humanoid") ~= nil then
	DetectedHumanoid = Hit.Parent:FindFirstChild("Humanoid")
	
elseif Hit.Parent.Parent.Name ~= Player.Name and Hit.Parent.Parent:FindFirstChild("Humanoid") ~= nil then
	DetectedHumanoid = Hit.Parent.Parent:FindFirstChild("Humanoid")
	
elseif Hit.Parent.Parent.Parent.Name ~= Player.Name and Hit.Parent.Parent.Parent:FindFirstChild("Humanoid") ~= nil then
	DetectedHumanoid = Hit.Parent.Parent.Parent:FindFirstChild("Humanoid")
	
elseif Hit.Parent.Parent.Parent.Parent.Name ~= Player.Name and Hit.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid") ~= nil then
	DetectedHumanoid = Hit.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid")
	
elseif Hit.Parent.Parent.Parent.Parent.Parent.Name ~= Player.Name and Hit.Parent.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid") ~= nil then
	DetectedHumanoid = Hit.Parent.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid")
end

That script is in a function obviously but its meant to detect the Humanoid in the fake ray when it hits an object if there is a Humanoid.

(The last elseif is where it is erroring)

Are you sure Hit.Parent.Parent.Parent.Parent.Parent isn’t nil and exists?

Yes it is not nil I put that if statement in an if Hit ~= nil then statement.

No, I’m talking about the object you’re trying to index with Hit.Parent.Parent.Parent.Parent.Parent, not the hit object itself because you might be trying to index the parent of the datamodel which is nil.

1 Like

OHHH Right I’ll try fix that and see if it helps