How to get the model of mouse.target

I’m trying to make a function return the model of a block. So basically a block in my game contains multiple parts, and the parts are parented into a model.
I’m struggling on how to get the actual model that holds all of the parts. The problem is that I can’t get the model using mouse.target since mouse.target doesn’t detect models, as it’s not a part of the world.

So I made a script that gets the first ancestor of a model, but if the object is in a model within the actual model, the function returns nil.

How would I make it so that the function actually returns the real model that contains everything?

Here’s my script.

function BuildServiceClient.getBlock(self: BuildServiceClient)
	local target = mouse.Target
	
	if not target then return end
	target = target:FindFirstAncestorWhichIsA("Model")
	if not target then return end
	
	if not target:GetAttribute("Object") and not target:GetAttribute("OwnerId") and target:GetAttribute("OwnedId") ~= player.UserId then return end
	
	return target
end

Your issue here is that you’re looking for a specific model. The easiest solution here (and there’s like 100 different things you could do) is to simply change your function to iterate through ancestor models until you find what you’re looking for:

function BuildServiceClient.getBlock(self: BuildServiceClient)
	local target = mouse.Target

	while target ~= nil do
		target = target:FindFirstAncestorWhichIsA("Model")
		if target == nil then
			return nil
		end

		local ownerId = target:GetAttribute("OwnerId")
		if target:GetAttribute("Object") ~= nil and ownerId ~= nil then
			-- We've reached our target model, so either return
			-- the target or nil at this point.
			return if ownerId == player.UserId then target else nil
		end
	end
	
	return target
end

Thanks man! I have thought of this, but my version wasn’t reliable. Also, I just noticed that you’re a youtuber that I’ve watched to learn OOP so that’s pretty sick. Ur observer video was really helpful btw, and I use it now for a game I’m making.