Search code examples
c#spritesprite-sheetgodot4

How to change the frame of an instatiated Sprite2D Godot using C#?


I am trying to instatntiate a Sprite2D Scene with 12 frames into my game and set the frame so that each instance uses a differnt frame. When I try to change the frame property I get a compiler error which states:

D:\Projects\Godot\Chess\Board.cs(22,12): 'Sprite2D' does not contain a definition for 'frame' and no accessible extension method 'frame' accepting a first argument of type 'Sprite2D' could be found (are you missing a using directive or an assembly reference?)

How do you modify this property?

My code is:

var pieceScene = GD.Load<PackedScene>("res://piece.tscn"); //This is the Sprite2D Scene
var wKing = pieceScene.Instantiate() as Sprite2D;
wKing.frame = 0;
AddChild(wKing);

I have also tried

var pieceScene = GD.Load<PackedScene>("res://piece.tscn"); //This is the Sprite 2d Scene
var wKing = pieceScene.Instantiate() as Sprite2D;
wKing.set_frame(0);
AddChild(wKing);

However they bring up the same error exept there is no defeniton for set_frame.


Solution

  • As the Godot C# API Differences Documentation states, most of the API for C# is in PascalCase compared to GDScript's API using snake_case. So in the case of Sprite2D.frame you want to use Sprite2D.Frame instead.