Trying to make a script that moves a gui button to the right when a player hovers with their mouse. Since there’s multiple buttons, I wanted to try and use a for loop instead of making a block of code for each individual button. So I had a variable setup to get each gui elements Y value so I could just use one loop.
for _, v in pairs (buttons:GetChildren()) do
local basePositionY = v.Position.Y
v.MouseEnter:Connect(function()
local info = TweenInfo.new(0.5,Enum.EasingStyle.Sine,Enum.EasingDirection.In,0)
print(basePositionY)
v:TweenPosition(
UDim2.new(0, 50, basePositionY),
"Out",
"Quad",
0.75,
true
)
wait(1)
print(v.Position)
end)
end
However, this just makes it so the gui elements float into the top of the screen.
I’m assuming this is because the basePositionY is inside of the loop but I honestly have no clue. Any help would be appreciate and such. If it is because basePositionY is in the for loop, does that mean it’s impossible to get a variables values if that variable is declared in the loop or is there a way around that?
Perhaps set basePositionY to be v.Position.Y.Scale and then tweening the button to UDim2.new(0, 50, basePositionY, 0)? Not sure if this will change anything, but the problem is definitely around the Y coordinates.
for _, v in pairs (buttons:GetChildren()) do
local basePositionY = v.Position.Y.Scale --change here
v.MouseEnter:Connect(function()
local info = TweenInfo.new(0.5,Enum.EasingStyle.Sine,Enum.EasingDirection.In,0)
print(basePositionY)
v:TweenPosition(
UDim2.new(0, 50, basePositionY, 0), --change here
"Out",
"Quad",
0.75,
true
)
wait(1)
print(v.Position)
end)
end
And for your question about getting variable values in loops:
As long as the variables are locally defined in the loop, each branch should have its own set of those variables.
For example:
for _, v in pairs (buttons:GetChildren()) do
local var = v.Position.Y.Scale
end
--Loop 1: var will be for example 10
--Loop 2: var might be something different, but will not change what loop 1's var store.