How would i get the first parent of a model?

So if I wanted to get the first parent of a model, how would i do it?

Example:
image

How would i get PARENT from CHILD?

2 Likes

child.Parent.Parent.Parent

lol

2 Likes

not like that lol, i mean like how would i make a function to always get the top parent

2 Likes

You can use a function that iterates through the parent hierarchy until it reaches the root:

function getTopParent(child)
    local current = child
    while current.Parent do
        current = current.Parent
    end
    return current
end

local topParent = getTopParent(child)
print(topParent.Name)

This function keeps climbing up the hierarchy until it finds the top parent. Give it a go and see if this is what you need.

4 Likes

When the instance is in any of the services, its highest ancestor will always be the datamodel (which the game variable refers to). If you want to get the ancestor that is either a child of a service or parented to nil, you can use the first one of these. If you want to get the ancestor that is a service (or nil if the instance is outside the datamodel), use the second function.

local function getHighestNonServiceAncestor(descendant: Instance): Instance
	local current: Instance = descendant
	while current.Parent ~= nil and current.Parent.Parent ~= game do
		current = current.Parent
	end
	return current
end

local function getServiceAncestor(descendant: Instance): Instance?
	local current: Instance = descendant
	while current.Parent ~= nil and current.Parent.Parent ~= game do
		current = current.Parent
	end
	return current.Parent
end
4 Likes

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