Checking if any parent of an object is a child of something

Heya!
I’ve been making a hover ui for my tower defense game (a ui that appears when hovering over an enemy or tower and displays things such as health).

I have encountered a problem, where it only works / displays the ui if the parent (enemy model) of the thing the raycast is hitting is a direct child of the enemy model folder.
The issue here is that if I have a models inside my enemy it won’t detect those models as “part” of the enemy which is kinda bad.

Hence I was wondering how I could check if any parent of an object (in this case result.Instance from my raycast) has the enemyModel folder as direct parent (so I can basically display the ui for all enemies, even if I hover over a part that’s inside a model inside the enemy model).

It would also be great if I could exactly identify WHAT model has the enemyModel folder as direct parent so I can later use that model’s name (in this case an ID) to get enemy health and such.

Does anyone have an idea???
Thanks!

You need to implement your own upward-searching function. You say there’s an overarching parent folder named “enemyModel” for each enemy, is this always named “enemyModel”? Do you perhaps have a tagging system with CollectionService?

1 Like

Well, the parent “folder” is a model.
It looks something like this:

“1” being the enemy model for the enemy
Bildschirmfoto 2025-01-04 um 18.22.43

And no, I don’t use collection service.

local function getEnemyModel(descendant: BasePart): Model?
    local parent = descendant.Parent

    while parent and parent.Parent ~= workspace.EnemyModels do
        parent = parent.Parent
    end

    return parent :: any
end

You can use the above function to get the child instance of the “EnemyModels” folder that contains the given descendant BasePart

1 Like

Oh wow I didn’t even know about this method. I’ll try it out! Thanks!
Also, do you perhaps have an idea on how I can “get” the enemyModel (in the image “1”)?
I’ll need it to get the data.

I’ve updated my reply to contain that solution instead. It’s more optimal as you can prevent your system from polling the same information about the enemy you’re already hovering over

Thanks!
Now I wonder, will this explode my pc if run every frame lol.

It won’t; you’d be surprised to see just how much is really being done every frame

1 Like

I’ve changed your code to instead of checking if parent exists and parent isn’t “EnemyModels” to check if parent exists and if parent.PARENT isn’t “EnemyModels”.

It would only return EnemyModels otherwise. Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.