Best practices for creating a Persistent Tween in Godot 4?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By aidave

Let’s say I have a shader effect when the player is hit, then fades away over a few seconds using a Tween. But if the player is hit again before that tween ends, we want to restart that tween from the beginning… not add a second tween!

Here is what I’m trying to do (in psuedo-code), but it doesn’t like it, and the tween never seems to finish.

ERROR: Tween (bound to …): started with no Tweeners.
ERROR: Tween invalid. Either finished or created outside scene tree.

var effect_tween: Tween

ready():
	effect_tween = create_tween()
	effect_tween.bind_node(self)
        effect_tween.connect("finished",Callable(self,"effect_completed"))

func play_effect():
    if effect_tween.is_running():
          effect_tween.stop()
    effect_tween.tween_property(...)
:bust_in_silhouette: Reply From: KoBeWi

Your code is almost correct. Create the Tween in play_effect() and use kill() if you want to stop the previous one. You don’t need to check if it’s still running.

var effect_tween: Tween

func play_effect():
    if effect_tween:
          effect_tween.kill()

    effect_tween = create_tween()
    effect_tween.connect("finished",Callable(self,"effect_completed"))
    effect_tween.tween_property(...)

btw create_tween() does already bind the node that called it.