I want to make a hover animation for every button in a frame, and was wondering how to do this with CollectionService. Does anyone know how to do it?
Is there any particular reason youâre wanting to use tags for this? I would be more inclined to use a for loop for the descendants/children of the frame and use an if statement to check if the instance is a button.
No, I just donât want to have duplicated scripts in each button. Could you make an example of what I should do?
Of course!
for i, v in pairs(frame:GetChildren()) do
if v:IsA("TextButton") then
v.MouseEnter:Connect(function()
-- do your hover animation
end)
end
end
This function will get every button that is a descendant of a given object.
You could iterate through itâs returned value to code every button at once
local function get_buttons(frame: Instance): {GuiButton}
local out= {}
for _, child in ipairs(frame:GetDescendants()) do
if child:IsA("GuiButton") then
table.insert(out, child)
end
end
return out
end
for _, button in get_buttons(script.Parent) do
tween_function(button)
end
Couple questions:
What is âoutâ for?
Does it have to be ipairs or can it just be pairs, because it looks like I can do it with pairs.
ipairs is marginally faster for arrays. you donât technically need either.
out
is defined to collect and return the GuiButtons
.
Ohh, okay. But sorry, last question, what does the
(frame: Instance): {GuiButton}
do? Iâm still kind of new to scripting.
These are type notations, a hidden feature of Robloxâs Luau. Add --!strict
to the top of your script and you will receive better errors before playing the game and much better auto-complete.
Those types are telling you that the parameter frame
must take an Instance
i.e. anything with a Parent/Children and returns an array of GuiButton
s i.e. clickable UI.
Wait, Iâve never heard of luau, does it have to be downloaded or is it already embedded into studio?
It is already in studio, Itâs Robloxâs expanded version of Lua. Adding --!strict
to the top of your scripts will enable the type checking aspects.
This did not work by the way. For the MouseLeave and MouseEnter parts, specifically.
How would I use MouseEnter and MouseLeave for this though?
local function get_buttons(frame: Instance): {GuiButton}
local out = {}
for _, child in ipairs(frame:GetDescendants()) do
if child:IsA("GuiButton") then
table.insert(out, child)
end
end
return out
end
local buttons = get_buttons(script.Parent)
for _, button in buttons do
local startSize = button.Size
local bigSize = UDim2.new(startSize.X.Scale * 2, 0, startSize.Y.Scale*2, 0)
local animationTime = 0.2
button.MouseEnter:Connect(function()
button:TweenSize(bigSize, Enum.EasingDirection.InOut, Enum.EasingStyle.Linear, animationTime, true)
end)
button.MouseLeave:Connect(function()
button:TweenSize(startSize, Enum.EasingDirection.InOut, Enum.EasingStyle.Linear, animationTime, true)
end)
end