How to Access a Sprite from code properly? C#

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

Alright I might be rusty in C#.
I’ve managed to figure out most of my problems with Godot’s C# either on my own or with a quick google.
But I’m stuck on this and I’m embarrassed.

The simple of it, is I need to Access a Sprite from code, specifically for its SetFrame().
But every time I try I’m getting " System.InvalidCastException: Specified cast is not valid.".
I am confused because I can grab the Node2D, Labels, pretty much anything else, but it yells at me if I even look the wrong way at a sprite.
I’ve used this way of doing it with Node2D and Labels and stuff
Sprite spriteName; spriteName = (Sprite)GetNode("pathtosprite");
and that works for most of what I need.
I’m also used to doing the following in C# normally-

spriteName = GetNode<Sprite>("pathtosprite");
but that is also yelling at me.
I don’t know, I’ve even tried using as Sprite as well, all of these in different combinations. Just frustrated. I’ve scoured the Docs, I’ve googled the hell out of it, I’ve tried every Solution I’ve seen so far. I’ve seen how easy it is in GDScript.
I’d love to understand what I’m messing up and how to do it properly.
And if this is so obvious and simple, I’m sorry I’m just very tired and can’t really think it out for some reason.

When I do get it to stop yelling at me that, it yells at me about E 0:00:01:0545 System.NullReferenceException: Object reference not set to an instance of an object.

Someone please help.
I’m sorry I’m a dumb.

Also got it stop yelling at me with spriteName = GetNode("nodepath") as Sprite;
forgot to add that.
But yea, null object reference. I don’t know whats happening.
I can grab every other object in my scene, but Sprites don’t like me.

shaggysays | 2020-02-12 04:25

I think it’s probably an Image, not a sprite.

or, the path is wrong. maybe check null, and then print the type (typeof keyword) before doing the cast.

Jason Swearingen | 2020-02-12 13:25

:bust_in_silhouette: Reply From: coBearCoding

Hi shaggysays, since I don’t have much information of your code I’ll just go and suggest the version of code that worked for me:

public override void _Physics_Process(delta){
  var spriteToGet = (Sprite)GetNode("NameOfMySprite");
   
}

with that code you can access all properties of an actual sprite, if you want to store a specific property of the Sprite then you can do this:

public class MyPlayer:KinematicBody2D
{
    private Texture spritePropertyToPassOver;
    
   public override void _Physics_Process(delta)
{
    var spriteToGet = (Sprite)GetNode("NameOfMySprite");
    spritePropertyToPassOver = (Texture)spriteToGet.Get("PathToProperty");
}

}

PD: You can use your property or calling the property of your instance in

any function, I’m just using the _Physics_Process as an example