C# - How to get data from a file of Resource type

Godot Version 4.3 Beta 1


I imported the resource into the script. Now I want to get data from the resource, i.e. its fields (see screenshot). How could I get data from the resource?

P.S. If there is a GDScript solution, that will work too, I will adapt it.

How do you mean you imported the resource? Into what script? Do you mean you assigned it in the editor to a property?

I mean this:

Resource loaded_resource = GD.Load<Resource>(path + file_name);

And I’d like to refer to resource fields, for example:

string name = loaded_resource.Name

But of course it doesn’t work and I’m looking for a solution :slight_smile:

You need to load it as your custom resource type, instead if Resource, so GD.Load<CellTemplate>

I tried it, but it doesn’t work. Here is the error:

E 0:00:01:0266 object System.Runtime.CompilerServices.CastHelpers.ChkCastAny(System.Void*, object): System.InvalidCastException: Unable to cast object of type 'Godot.Resource' to type 'Template'.

My bad it autocorrected: GD.Load<CellTemplate>

No, you wrote everything correctly, it’s just that I have two scripts. One is GDScript and the other is C#. Based on GDScript I create resources in the editor itself, because using C# there is no button to create a resource.

I guess I should have written about it, my mistake.

Here are both codes:


extends Resource
class_name Template

@export var name: String = "Error"
@export_enum("Code", "World", "Ground") var type: = "Code"

@export var icon_name: String = "error"
@export_enum(".png") var icon_type = ".png"

@export var texture_name: String = "error"
@export_enum(".png") var texture_type = ".png"

@export var is_destructible: bool = false

@export var collision_layers: int
@export var collision_masks: int
#@export_flags_2d_physics var collision_layers
#@export_flags_2d_physics var collision_masks

@export_enum("1x1", "2x2", "3x3") var size = "1x1"
@export var count_cells: int = 1


using Godot;

public partial class Template : Resource
    public string name;
    public string type;
    public string icon_name;
    public string icon_type;
    public string texture_name;
    public string texture_type;
    public bool is_destructible;
    public int collision_layers;
    public int collision_masks;
    public string size;
    public int count_cells;

You need to make it a global class

I apologize for writing nonsense in the question. Well, I found the answer. The Resource fields can be accessed by calling the Get(“FIELD_NAME”) method;

For example:

Resource resource = GD.Load<Resource>("path");
string name = (string)resource.Get("name");

P.S: There’s more information about cross-language development here

1 Like