How to spawn a one-shot sprite effect in Godot 4 that cleans itself up
Short answer
Instance an AnimatedSprite2D with your effect's SpriteFrames (loop off), add it to the current scene at the hit position, call play(), and connect animation_finished to queue_free so it removes itself.
- Make a SpriteFrames animation for the effect with Loop off.
- Instance an AnimatedSprite2D, set sprite_frames and global_position.
- Add it to the current scene (not the enemy, which may be freed first).
- Play it and connect animation_finished to queue_free.
Copy-paste code
GDScript
func spawn_fx(frames: SpriteFrames, anim: String, at: Vector2) -> void:
var fx := AnimatedSprite2D.new()
fx.sprite_frames = frames
fx.global_position = at
get_tree().current_scene.add_child(fx)
fx.animation_finished.connect(fx.queue_free)
fx.play(anim)Flarewick VFX: Pixel explosions, slashes and magic, ready to drop in
from $7Flarewick ships 15 effects in 48 colourways with a FlarewickFX.spawn() one-shot helper that does exactly this, for $7.
Secure checkout · 14-day fix-or-refund if it doesn't work as described (terms)Questions
Why add it to the scene and not the enemy?
If the enemy is freed on death, a child effect would vanish with it.
Free: the Roblox Starter Kit
7 free Luau modules (damage, pets, shop formatting, admin audit log, tycoon guards and more) plus 3 free calculators, then 5 short emails with the scripting fixes we see go wrong most often.