This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

Hello. Brand new to Godot but I work with .Net at my day job so I'm trying to learn the engine with C#. I'm having trouble dealing with custom classes derived from Godot built-in classes. Example:

using Godot;
using System;

public class Item : Resource
{
    [Export]
    public String name = "";

    [Export]
    public Texture texture;
}

My Item class inherits from Godot's Resource class and adds two props. Elsewhere I am trying to load Resource objects and convert them to my Item:

[Export]
public List<Item> items = new List<Item>(new Item[9]); // Invalid cast error
items[itemIndex] = item;

public Item SetItem(int itemIndex, Item item)
  {
        var previousItem = items[itemIndex] as Item; // Invalid cast error
        items[itemIndex] = item;
        List<int> itemIndexList = new List<int>();
        itemIndexList.Add(itemIndex);
        EmitSignal(nameof(ItemsChanged), itemIndexList);

        return previousItem;
   }

When using the ResourceLoader.Load() method, my objects come back as Resources, specifically TextureStreams. I get that casting from Resource to Item (Parent to Child) is invalid for C#, but seems the standard in all the GDScript examples. What's the intended way to work around this strictness in C# with Godot's native types?

Godot version 3.5
in Engine by (12 points)

1 Answer

0 votes

Hello dinotope,

yeah, forget about inheritance for resources!

Better Create a Class and add the resource as property:

using Godot;

public class Item
{
    public Texture Texture { get; set; }
    public string Name { get; set; }
}

-

var item = new Item { Texture = GD.Load<Texture>("res://icon.png"), Name = "icon" };
by (1,081 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.