Assigning @onready variables to a variable

Godot Version

4.2.1

Question

Hi! This might be a very dumb question, but I can’t find an answer to it online.

I want the player to have different classes he can choose from, each with their own unique AnimatedSprite2D node where I can keep all of their custom animations, and I’ve made an exp class and a sam class so far.
I’ve made some identical animations, such as “running_right”, and since I don’t want to bloat the code by rewriting for example .play(“running_right”) for every class node and checking which one it should run, I’ve created another general variable, “anim_sprite”, which I want to assign the @onready variable of the player’s AnimatedSprite2D class to (either exp or sam).
So something along these lines:

var anim_sprite = exp_sprite

@onready var exp_sprite : AnimatedSprite2D = $ExpSprites
@onready var sam_sprite : AnimatedSprite2D = $SamSprites

func change_class():
if anim_sprite == exp_sprite:
anim_sprite = sam_sprite
else:
anim_sprite = exp_sprite

Then have another function use anim_sprite.play(“running_right”) when the player moves to the right

But no matter how I rewrite the code, it always gives me an error saying it can’t use .play() on Nil or null, which makes me think I just have no idea what I’m doing. How could I fix this? Thanks in advance.

I fixed it after a few tries myself. I had to specify anim_sprite to be an AnimatedSprite2D on its variable:

var anim_sprite : AnimatedSprite2D, then assign it with one of the @onready variables

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.