How to find the first ancestor of an object with a certain tag?

How would I find the first ancestor of, lets say, a proximityprompt instance, that has a certain tag?
Like this for example, how would I find this AncestorWithTag?
image

1 Like

You would have to use the CollectionService to reference the tags and then loop through the Ancestors to compare them:

local CollectionService = game:GetService("CollectionService")

-- Function to find the first ancestor with a specific tag
local function findAncestorWithTag(instance, tag)
	local currentInstance = instance
	while currentInstance do
		if CollectionService:HasTag(currentInstance, tag) then
			return currentInstance
		end
		currentInstance = currentInstance.Parent
	end
	return nil -- No ancestor with the specified tag was found
end

local proximityPrompt = script.Parent -- Assuming the script is a child of the ProximityPrompt
local tag = "yourTag" -- Replace with the tag you're looking for

local ancestorWithTag = findAncestorWithTag(proximityPrompt, tag)
if ancestorWithTag then
	print("Ancestor with tag found: " .. ancestorWithTag.Name)
else
	print("No ancestor with the tag found.")
end
1 Like

Afaik there is no built in function, but something like this should work:

local function FindFirstAncestorWithTag(instance : Instance, tag : string) : Instance?
    repeat
		instance = instance.Parent
	until not instance or instance:HasTag(tag)
	
	return instance
end
3 Likes

Thanks a ton, it works perfectly.

1 Like

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