Tween Guis Doesn't Callback The Function after The Tween Finishs

Hey,
My issue here that callback function called once the tween starts not after when it completes.

Code:

local function setTwitterCodesGuiVisiblity(status)
twitterCodesGui.Visible = status
end

twitterCodesButton.MouseButton1Click:Connect(function()
if twitterCodesGui.Visible == false then
	setTwitterCodesGuiVisiblity(true)
	twitterCodesGui:TweenPosition(UDim2.fromScale(0.5,0.7), Enum.EasingDirection.Out, Enum.EasingStyle.Elastic, 0.5)
else
	twitterCodesGui:TweenPosition(UDim2.fromScale(0.5,1.1), Enum.EasingDirection.In, Enum.EasingStyle.Elastic, 0.5, true, setTwitterCodesGuiVisiblity(false))
end
end)

That’s because the way your code is getting evaluated is that the setTwitterCodesGuiVisibility function gets ran in the statement first and then the returned value is passed as the final argument in TweenPosition. It’s expecting a function but it’s getting returned nothing so it doesn’t actually have a function to run. Your code is functionally equivalent to this:

local function setTwitterCodesGuiVisibility(status)
    -- other code
    return nil
end

print(setTwitterCodesGuiVisibility) -- nil

TweenPosition’s final argument accepts a function value. You cannot pass arguments to this callback, it gets called internally and if any arguments need to get passed then it happens there as well. Your callback functions for TweenPosition will only get called if you pass the variable like so:

obj:TweenPosition(args, setTwitterCodesGuiVisibility)

This passes the actual function to TweenPosition rather than what the function returns (which is void because it doesn’t return anything). In this case though, you lose the ability to specify arguments for the function. So two options: change the function itself:

--- Change visibility of codes Gui with optional boolean for state.
-- If no value is passed, assume we should make the status false and hide Gui.
-- You may need to check the parameter's type if non-booleans are passed.
local function setTwitterCodesGuiVisibility(status)
    local status = status or false
    twitterCodesGui.Visible = status
end

Or use TweenService, which is the new standard for operating tweens on instances and should also be used over the Gui methods as TweenService can do everything these Gui methods can and more.

TweenService will give you an actual tween object to control playback. You can also use its Completed event for an event-based approach to this problem. Completed passes a PlaybackState Enum to functions, so you can check if Completed was passed and then do something.

You’d be on your own to figure out how to incorporate TweenService if you want to switch over. I recommend reading documentation and testing to find something that works. Otherwise, answer for continuing to use TweenPosition is above. :slight_smile:

2 Likes