Accessories causing script errors

I’ve set up a raycast melee system, and it works, most of the time. Upon introducing accessories, specifically ones that are applied to the body, such as waist and back accessories, the script becomes unreliable.

This is the specific part that the error occurs in, it is not the entire script.

		local hit, Pos = workspace:FindPartOnRay(r, hum.Parent)
		
		if hit then
			if hit.Parent:FindFirstChild("Humanoid") ~= nil or hit.Parent.Parent:FindFirstChild("Humanoid") ~= nil then
				target = hit.Parent["Humanoid"] -- error occurs here
			end
			break
		end

If the player were to hit another players accessory, or accessories, rather than their limbs or torso, this error occurs:

> Humanoid is not a valid member of Accessory “Workspace.Dummy.Accessory”

I understand why this is happening, the script is looking for a humanoid within the accessory, rather than the players character. The issue I’m having is figuring out how to avoid the error all together.

Consider FindFirstAncestorOfClass(“Model”) and checking if there’s a Humanoid if that call doesn’t return nil instead. Alternatively you could go through relevant characters either via Players or CollectionService, the latter to account for NPC characters, and check if the hit part is a descendant of the character of the current iteration of a for loop.

Okay, so I added FindFirstAncestorOfClass() and got this

if hit then
			if hit.Parent:FindFirstChild('Humanoid') ~= nil or hit.Parent.Parent:FindFirstChild('Humanoid') ~= nil then
				target = hit:FindFirstAncestorOfClass("Humanoid")
			end
			break
		end

The error no longer appears, so that’s cool. It just doesn’t damage the player that was hit, it doesn’t even seem to pick up the humanoid, which is weird.

You’re not supposed to use the FindFirstAncestor method to check for the Humanoid. You’re only supposed to do that to check for a character model which then you can in turn check for a Humanoid in the character if one does exist.

if hit then
    local character = hit:FindFirstAncestorOfClass("Model")
    if not character then return end

    local humanoid = character:FindFirstChildOfClass("Humanoid")
    if not humanoid then return end

    -- process humanoid or whatever
1 Like

Ahh, gotcha. I’d never used that until now so I was a tad bit confused on it’s usage. Thanks for clearing it up, I feel kinda stupid now heh.