(C#) Getting InvalidCastingExceptions when instancing scene.

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

I’m trying to instance an Entity Scene, which is extended from Sprite.

Map:

namespace Core {
public class Map : TileMap
{
    public PackedScene EntityScene;
    Entity[,] grid;

    public override void _Ready()
    {
        EntityScene = ResourceLoader.Load("res://scenes/Entity.tscn") as PackedScene;
        grid = new Entity[16,16];
        GD.Print("Map Ready!");

        Entity entity_inst = (Entity) EntityScene.Instance();
        AddChild(entity_inst);
        InsertEntity(entity_inst, 10, 10);
    }

    public void InsertEntity(Entity ent, int x, int y)
    {
        grid[x, y] = ent;
        ent.SetGridPosition(x,y);
    }
}

Entity:

namespace Core {
public class Entity : Sprite
{
    private TileMap map;
    private Vector2 gridPosition = new Vector2();
    public override void _Ready()
    {
        map = (TileMap) GetParent();
    }

    public void SetGridPosition(int x, int y)
    {
        gridPosition.x = x; gridPosition.y = y;
        SetPosition(new Vector2(x * 32, y * 16));
    }
}

I’ve looked at other Godot C# examples, but using custom node classes shouldn’t be a problem…

Which line is causing the error?

Zylann | 2018-06-26 12:41

Main
Entity entity_inst = (Entity) EntityScene.Instance();

prixt | 2018-06-26 12:52

Is the root of your scene having the Entity script on it?

Zylann | 2018-06-26 18:27

Yes, the Entity.cs is attached to the Entity node, which is the root of its scene.

prixt | 2018-06-27 09:17

That looks like a bug then. I’m not experienced in the C# integration of Godot though.

Zylann | 2018-06-27 18:48

nvm, found the problem; the class name must be the same as the script name. I first started the script as ‘EntityScript’ and so on, so it didn’t register. basic c# mistake.

prixt | 2018-06-29 11:07

Oh… well in that case it’s something to know about Godot. In C# you can name your classes the way you like, but Godot won’t recognize scripts for which the filename doesn’t match the class name (which means the special logic Godot runs to make this cast work is not finding the Entity class, even if C# compiles it fine).

Zylann | 2018-06-29 18:13