I'm using the action RPG tutorial by Heartbeast to learn Godot. Instead of using GDScript I'm using C#. Mostly because I prefer the language and it was an interesting challenge to convert the code to C#. The code was working fine up until now, but suddenly I have a strange issue with casting. Just wondering if anyone has any idea on what's going on.

It involves an scene called bat, which is an enemy type. The bat has an AnimatedSprite for the graphics. In the script attached tot the bat scene I get the AnimatedSprite object with the following line, but that gives a cast error. // At the start of the script: AnimatedSprite animatedSprite = null;

// in the _Ready() function: animatedSprite = GetNode<AnimatedSprite>("AnimatedSprite);

This throws an error in the debugger: System.InvalidCastException: Specified cast is not valid.

I've done some debugging already to try to figure this out. I have changed it so that instead of casting it, I just retrieve the node. Node animatedSprite = GetNode("AnimatedSprite"); This works for the most part. Except for when I want to change a specific parameter of the AnimatedSprite object. (In this case: flipH) I checked the class of the Node: GD.Print(animatedSprite.GetClass());

Which prints: AnimatedSprite

But afterwards when I try to cast it like below, I get the same invalid cast exception. AnimatedSprite castAnimatedSprite = (AnimatedSprite)animatedSprite; The weirdest thing is that this has worked before. Anyone have any idea what could be the problem here?

I poked around a bit in Google.

Try AnimatedSprite castAnimatedSprite = getNode("Name") as AnimatedSprite

https://www.reddit.com/r/godot/comments/f2m25q/cant_access_sprite_in_c_i_have_no_clue_why/

I also have the same issue. In my case, I am using AnimatedSprite. After debugging, the following works: GetNode<Godot.AnimatedSprite>("...") GetNode<Godot.Sprite>("...") Reason: I had another AnimatedSprite script class named as AnimatedSprite. When I do GetNode<AnimatedSprite>("..."), C# is trying to cast it to my other AnimatedSprite class. What I should do is to cast the node to Godot.AnimatedSprite or rename my other AnimatedSprite class to other name.

Thanks Dotted. That was indeed the problem. I had forgotten about a script I created and disconnected called AnimatedSprite.cs. So I fixed it by removing that.

2 years later