Checking every parent to see if it contains an object

For example I have a part here with tons of different descendants:
Screenshot 2022-02-12 at 8.21.12 PM
Now, I have another function that detects what object the cursor is touching ( hovering on ).
I do know that I can detect if the object that the cursor is touching’s parent contains TargettedThing by doing something like

if touching.Parent:FindFirstChild("TargettedThing") then
  --blah
end

But the question is: What if I’m not directly touching a child of the MainPart? What if the cursor is touching SmallPart? I want it so that it can detect all the touched object’s parent and if they contain “TargettedThing” or not. How can I do this?

help will be appreciated :smiley:

local function FindLastAncestorOfClass(object, class)
	local ancestor = object:FindFirstAncestorOfClass(class)
	if ancestor then
		FindLastAncestorOfClass(object, class)
	elseif not ancestor then
		return ancestor
	end
end

This is a generic function for finding the last ancestor of a particular class.

local Object = CursorPart
local AncestorName = "MainPart"
local Ancestor = Object:FindFirstAncestor(AncestorName) --recursively checks the object parents, until nil or MainPart is reached

if Ancestor then
	print(Object.Name.." is a member of "..AncestorName)
	local TargettedThing = Ancestor:FindFirstChild("TargettedThing", true) --recursively searches for "TargettedThing" inside Ancestor
	print(TargettedThing)
else
	print(Object.Name.." isn't a member of "..AncestorName)
end

I get what this code does, however I do not have the AncestorName in the code ( since I am checking if the touched item’s parent contains an object, and I do not know the touched item’s parent’s name ). Hmm?

AncestorName in the code that was posted, is the highest root part (Ancestor) of your collection of nested parts.

Such as… where will these parts be? In your example picture they seem to be all under a part named MainPart.

function FindThing(part, thingName)
	local thing = part:FindFirstChild(thingName)
	if thing == nil then
		if part.Parent ~= workspace then
			return FindThing(part.Parent,thingName)
		end
	end
	return thing
end


local targettedThing = FindThing(touching,"TargettedThing")
if targettedThing then
	print("found the thing")
end

I should have used another example, for example MainPart is a folder and you can’t move your cursor on it in game, that is why I need to detect the cursor touched object which should be either Part or SmallPart and check if TargettedThing’s Parent is same with the cursor touched object’s parent.
However, if my cursor is on SmallPart then this thole thing doesn’t work, since SmallPart’s Parent’s Parent is Mainpart.

The code I put should work for that, as it doesn’t check for BasePart, it only checks for a child with the correct name as it moves up the tree.