How do I queue free a tween stored in a variable?

Godot Version

v4.3.stable.official

Question

Hi, How am I supposed to queue free a tween stored in a variable like this?

var tween = create_tween()

This is what I’ve tried:

print(tween)
tween.stop()
tween.tween_callback(queue_free)
print(tween)

The output is:
<Tween#-9223371989660465276> (bound to Player)
<Tween#-9223371989660465276> (bound to Player)

I’m not that experienced, I think this means that the tween still exists? Any help will be appreciated :slight_smile:

You cannot queue_free tweens as they are not Nodes, they’re of type RefCounted, and as the documentation says:

Unlike other Object types, RefCounteds keep an internal reference counter so that they are automatically released when no longer in use, and only then. RefCounteds therefore do not need to be freed manually with Object.free().

So you don’t have to worry about freeing tweens.
As for why your code behaves like that: when calling queue_free, you don’t free the tween but the node it’s been called by (the player). The tween will be freed from memory once not being useful anymore, automatically.

2 Likes

Your tween will be freed when the node it is on is freed, or if you call the kill() function. The reason that you still get the Tween printed out is that the object it belongs to is not freed right away (the Tween is reset by the stop() function and also queue_free is queued until the end of the current frame).

1 Like

As @paintsimmon said, tween.kill() is the answer.

Make a node2D with a sprite as a child and and attach a script:

extends Node2D

@onready var TestSprite: Sprite2D = $Sprite2D

var tween: Tween
var initial_position: Vector2 = Vector2(50, 50)
var target_position: Vector2 = Vector2(500, 500)
var tween_duration: float = 5


func _ready() -> void:
	TestSprite.global_position = initial_position
	tween = create_tween()
	tween.tween_property(TestSprite, "global_position", target_position, tween_duration)


func _input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_accept"):
		tween.kill()
		print(TestSprite.global_position)

Kills the tween as expected when you hit the enter key.

2 Likes