Excluding scripts when getting a random Child from a ScreenGui using math.random?

Hey! I’m trying to display a random ImageLabel from a ScreenGui using the script below, but the issue is sometimes it selects the LocalScript in the ScreenGui as the GUI it has to display because it’s a Child of it and there is no filter as to what it can select. Any help on how to make it so it’s unable to select scripts OR it’s only able to select ImageLabels would be appreciated.

Code:

local GUIs = PlayerGui:WaitForChild("ConfirmationUI"):GetChildren()
		local RandomGui = GUIs[math.random(1,#GUIs)]
		RandomGui.Visible = true

Setup:
image

simple, if the selectedobject:IsA(“LocalScript”) then, redo the process until it dosent pick the script.

1 Like

A rough idea of how you would do it.

local function pick()
	local RandomGui = GUIs[math.random(1,#GUIs)]
	if RandomGui:IsA("Script") or RandomGui:IsA("LocalScript") then
		pick()
		return
	else
		print("done")
		RandomGui.Visible = true
	end
end
pick()
4 Likes

Thanks! I was thinking of doing this but didn’t know how, I was about to ask how but I see @keztc has responded below. Thanks for your help. :slightly_smiling_face:

1 Like

@keztc has provided the exact same solution as mine but in a script form, you can mark him as solution

1 Like

This works fine, just a few things to note, math.random(1, #GUIs) is the same as math.random(#GUIs), if you prefer to include the 1 for the sake of clarity/readability then that’s understandable. When math.random() is called with one argument, i.e; math.random(5), the minimum value of the range is always 1 and the maximum value of the range is whatever value is passed as the single argument to the function (5 in this case).

The base class for all script instances is the “BaseScript” class, this class is the base class for all script instance types; server, local & module (which your script doesn’t cover). Instead of checking for each of these types individually we can simply check if the instance is a member of a class which inherits from the aforementioned base class.

local Gui = script.Parent

local function PickRandom()
	local GuiChildren = Gui:GetChildren()
	local RandomChild = GuiChildren[math.random(#GuiChildren)]
	if RandomChild:IsA("BaseScript") then
		PickRandom()
	else
		return RandomChild
	end
end
1 Like