Unsafe Method Access when using static typing

Godot Version

4.2

Question

Hi, I’m pretty new to programming in general, sorry if it’s a stupid question.
I’m trying to use GDscript as a statically typed language.

consider this code:

if direction.x > 0:
		get_node("AnimatedSprite2D").play("steering_right")

Since I enabled the warnings in the editor, i get this warning:

The method "play()" is not present on the inferred type "Node" (but may be present on a subtype).
  <GDScript Error>UNSAFE_METHOD_ACCESS

In this case, how would i tell the compiler that “AnimatedSprite2D” is an AnimatedSprite2D node? I don’t want it to infer what it is.

I tried

get_node("AnimatedSprite2D": AnimatedSprite2D).play("steering_right")

But it won’t accept it, it says

Line 12:Expected closing ")" after call arguments.
Line 12:Expected end of statement after expression, found ":" instead.

So obviously it’s not the way to do it.

I tried reading the Docs but I cannot figure it out.

Any help?
Thanks!!!

I think it would be best to just create a typed “@onready” reference to AnimatedSprite2D (drag&drop the sprite node into the code while holding ctrl) and call play() on that.
It’s better to do that anyway for nodes that you use often since get_node() is a relatively slow way to reference nodes.

1 Like

Great, it worked. No more warning! Thanks

1 Like

You can use as to cast to another type.

if direction.x > 0:
		(get_node("AnimatedSprite2D") as AnimatedSprite2D).play("steering_right")
2 Likes

You can use [as]

Hey man, thank you so much.
This was my intuition, but I didn’t know i needed to use parentheses!
It was giving me an error

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