Check if any ancestors have attribute

Hello devs, I am wondering if there’s a way to check if any of a parts ancestors (its parent, and their parent and so on). How could I achieve this? Any help is appreciated.

I basically want a better version of this.

if v.Parent:GetAttribute("Vulnerable") or v.Parent.Parent:GetAttribute("Vulnerable") or v.Parent.Parent.Parent:GetAttribute("Vulnerable") then
end
2 Likes

Try this (hope it works)


local function findPart(v)
local mainPart  = v.Parent

for _,v in pairs(mainPart.Parent:GetChildren()) do
       if not v:GetAttribute("Vulnerable") then mainPart = mainPart.Parent else return true end
end
end

if it finds the part then it will return true, so make a variable and if its true then do the rest of your code

Sorry to say that it didn’t work. I read the code and it isn’t really what I’m trying to achieve. I want to check if a parts parent has an attribute, and if it doesn’t, then if that instance’s parent has an attribute, and so on. Do you know how I could do this?

1 Like
local current_part = script.Parent.Parent -- start point
local attribute = nil

while true do
	task.wait(2)
	attribute = current_part:GetAttribute("Vulnerable") -- check if it has the attribute
	
	if attribute ~= nil then -- break the loop if it does
		break
	end
	
	current_part = current_part.Parent -- if it doesn't, update the current_part to the current_part's parent
	
	if current_part == nil or not current_part:IsA("BasePart") then -- if the part's parent is nil or it's not a part then break the loop (you can change this)
		break
	end
end

This checks if current_part has the attribute. If it doesn’t, then it changes current_part value to its own parent and checks again until it becomes nil or it’s not a Part.

1 Like

Try this:

-- Returns true if the object has an ancestor with the attribute equal to value.
-- If value is not provided, returns true as long as the attribute is not falsey (nil or false)
local function doesAncestorHaveAttributeEqualTo(obj: Instance, attribute: string, value: any?): boolean
	local ancestor = obj.Parent
	while ancestor do 
		if 
			value and ancestor:GetAttribute(attribute) == value 
			or ancestor:GetAttribute(attribute) 
		then 
			return true	
		end
		
		ancestor = ancestor.Parent
	end
	return false
end
1 Like

oh i see the problem with the code, i forgot something. im too lazy to fix it though. goodluck

This and @hellie_jellie solution works, im just gonna mark yours as solution because i dont really want it to be in a while true loop. Tysm @Riesegarder and @hellie_jellie!

1 Like

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