How to loop through a model to find a specific instance

How would I go about looping through a model to find a specific instance? I am making a system where bullets can damage a health pool of a model.

Example of what I want:
If the part hit is in a model within the model where the health value is kept, I could just do hit.Parent.Parent. However, if another part in the model is hit which is a descendant of a model within a model within a model that holds the health value, how would I get that too. Should I just do a bunch of if statements or is there a way to cleanly loop through every ancestor besides the workspace to find the value? The furthest I got with this is a script that crashed roblox when trying to check through the parents.

You can use either a loop or a recursive function to achieve this. They will keep going up in the hierarchy until they find the parent with the health value as a child. They’ll abort as soon as they find it or if they don’t find it at all.

--Loop
local currentParent = damagedPart
local parentWithHealth = nil
while currentParent do
   if(currentParent.healthInstance) then
       parentWithHealth = currentParent
       break
   else
       currentParent = currentParent.Parent
   end
end
--Do stuff with the parentWithHealth that you got


--Recursive Function
local currentParent = damagedPart
local parentWithHealth = nil
local function lookForParentWithHealth()
    if not currentParent then return; end
    if(currentParent.healthInstance) then
       parentWithHealth = currentParent
       return
   else
       currentParent = currentParent.Parent
       lookForParentWithHealth()
   end
end
lookForParentWithHealth()
--Do stuff with the parentWithHealth that you got

You can use the second argument of :FindFirstChild(ChildName,CheckDescendants) to get an object by name that’s a descendant of something.