Why, in tutorials, people always create a variable to access animation nodes?

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

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?

:bust_in_silhouette: Reply From: kidscancode

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.

  1. 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.

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.

PapaSolidus | 2020-11-01 19:57

1 Like