Finding a matching descendant in two instances

Hello, I wanted to make a function that does the following:
Lets say i have two instances, and both have the exact same descendants and everything.
The function is supposed to be able to use a descendant from the first instance, and then find that matching descendant from the second instance by going through all of the part’s ancestors and making sure the names match until the main instance is reached (in order to stop it before it goes past where it should go) and then output it.

I attempted to create a function to meet my requirements:

local function findmatchingdescendant(instance, findfrom, findin)
    if not instance:IsDescendantOf(findfrom) then
        warn(instance.Name .. " is not a descendant of " .. findfrom.Name)
        return nil
    end
    local path = {}
    local current = instance
    while current ~= findfrom do
        table.insert(path, 1, current.Name)
        current = current.Parent
    end
    print("Path to follow: " .. table.concat(path, " -> ")) -- attempt to debug
    local match = findin
    for i,v in path do
        match = match:FindFirstChild(v)
        if not match then
            warn("No matching descendant found in " .. findin.Name .. " for " .. instance.Name)
            return nil
        end
        print("Found match at step " .. i .. ": " .. match.Name) -- attempt to debug
    end
    return match
end

The issue is that the findin argument is somehow different when I print it out, meaning it changes somewhere, but I cannot figure out how this is happening.

If anyone can help me out to make this function work properly, it would be greatly appreciated!

Maybe just using .Parent will work.

I put together a quick test file to show what I mean:

-- Searching for an Ancestor with a BoolValue that is TRUE


local Start_Here = script:WaitForChild("Start_Here").Value
local Current = Start_Here
local Found = false

repeat
	task.wait(1)

	if Current.Parent:FindFirstChild("BoolValue") then
		if Current.Parent.BoolValue.Value == true then

			print("Found in", Current.Parent.Name)

			return
		else

			Current = Current.Parent

			print("Searching...", Current.Name)

		end
	end

until Found == true

Screen Shot 2024-04-13 at 5.49.50 PM

Screen Shot 2024-04-13 at 5.50.05 PM

Test.rbxl (54.4 KB)

1 Like