Get all Objects with Tag to Highlight

I am making a module that calls for every object in a folder with the tag Shelf. When this is returned true, a child of the object, a Highlight (present in all models) is supposed to be activated. However, only one model’s highlight is activated, not the remaining ones.

This is the function:

function module:CheckForTag(Folder: Folder, Tag: string)
	for _, Object in ipairs(Folder:GetChildren()) do
		if Object:HasTag(Tag) then
			return true, Object
		else
			return false
		end
	end
end	

This is my server script:

local Module = require(script.Parent.ModuleScript)

local CustomObjects = game.Workspace.CustomObjects
local Status, Object = Module:CheckForTag(CustomObjects, "Shelf")


if Status == true then
	print("true")
	
	local highlight = Object:FindFirstChildOfClass("Highlight")
	
	highlight.Enabled = true
else
	warn("no")
end

Any help is greatly appreciated!

1 Like

You returned on the first one found which ends the script early. I believe that is the problem that you are looking for.

It’s because you’re returning the moment you find an object that has the tag. When you have a return statement inside of a loop, it ends the loop immediately.

You could just do this inside of your server script:

local function setHighlightsEnabled(container: Instance, tag: string, enabled: boolean)
    for _, model: Model in pairs(container:GetChildren()) do 
        if (model:HasTag(tag)) then
            local highlight = model:FindFirstChildOfClass("Highlight")
            if (highlight) then
                highlight.Enabled = enabled
            end
        end
    end
end

setHighlightsEnabled(CustomObjects, "Shelf", Status)

But I assume you have a ModuleScript for a reason, so if you want to throw that function into your ModuleScript:

function module:SetHighlightsEnabled(Folder: Folder, Tag: string, enabled: boolean)
	for _, Object in ipairs(Folder:GetChildren()) do
        if (not Object:HasTag(Tag)) then continue end
		local highlight: Highlight? = Object:FindFirstChildOfClass("Highlight")
        if (highlight) then
            highlight.Enabled = enabled
        end
	end
end
1 Like

Something to add would be of you wanted to avoid this problem, then you could wait until the for loop has completed to then return a table with all the objects with the tag, or an easier approach would just be using collection service.

If you have other highlights around the map, it could because of the highlight limit IN STUDIO.

Thank you! It is such me to overlook that, been a while since I have scripted :sweat_smile:

3 Likes

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