+1 vote

Learning through tutorials it seems a common practice to store animation nodes in a variable, like this:

onready var animatedSprite = $AnimatedSprite
func _ready():
animatedSprite.play("Explosion")

Why would that be a good practice? If I'm doing nothing complex, I'm only coding inside the scene itself, wouldn't calling the Sprite/AnimatedSprite/(etc) node directly sufice?

in Engine by (18 points)

1 Answer

+3 votes

There are two reasons people do this:

1) Convenience/flexibility

If your path/name to your animated sprite node changes, you'll only have to change it in one place, not throughout your code. This is of course only a benefit if you are going to access that node multiple times.

2) Performance

Caching the node reference in a variable could provide some minor performance benefit, although it's debatable whether the impact would be negligible. Again, only a benefit if you're accessing the node multiple times in your script.

by (22,067 points)

Thanks! That's what I thought, but as the tutorials themselves never went farther then one simples access to the node, I was confused if people were doing this out of habit (always covering the bases before the code got more complex) or if I was missing something.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.