Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Descendant of an Instance with Classname "x"?

I'm looking for a function/roblox function that will check if an instance is a descendant of an instance with a classname "x".

I have created the function as such however I do not know if this is the best way for the system...

Confirmation or an alternative would be great.

-- This function assumes that the user deems the Instance's class as irrelevant

local function DescendantOfInstanceWithClass(Instance,Classname)
	repeat
		wait()

		Instance = Instance.Parent

		if Instance:IsA(Classname) then
			return true
		end

	until Instance.Parent = game
	
	return false 
end

1 answer

✓ Accepted answer

There is object:FindFirstAncestorOfClass(className) and object:FindFirstAncestorWhichIsA(className) which return the ancestor of class className. Returns nil if no ancestor of that class was found.

local function DescendantOfClass(object, className)
    return object:FindFirstAncestorOfClass(className) and true or false
end

print(DescendantOfClass(game:GetService("Players"), "DataModel")) --> true

My function returns true if ancestor was found, false otherwise. I used the Players service and the DataModel (aka game) as a quick example.

1 comment

0

Ahhhhhhhhhh this is exactly what i was looking for i thought there was something wrong with me... it's way too late i guess ahaha thanks for the great answer!

This discussion is preserved as it was. New answers, comments, and votes are closed.