C# Godot / Compiler crashes when trying to add nodes via code

shinXdxdshinXdxd Posts: 6Member
public class Block : StaticBody2D
{
    private BlockType type {get;}
    // private Sprite sprite = new Sprite(); // this line causes a crash

    public Block(BlockType type, Vector2 position)
    {
        this.type = type;
        this.Position = position;
       // crashes somewhere on the next lines
        Sprite sprite = new Sprite();
        sprite.Texture = (Texture) GD.Load("res://assets/earth.png");
        this.AddChild(sprite);

    }

I'm trying to add nodes to a scene via Code. But the code crashes when trying to create objects of some classes like sprites. It also crashes if I want to add another Object as a class-member.

I don't know why the compiler (or godot) crashes on something trivial like Sprite sprite = new Sprite()
How can I do this so I can compile my project?

Comments

  • cyberealitycybereality Posts: 1,454Moderator

    Should that line be:

    var sprite = new Sprite();
    

    Sorry I use GDScript, but I did a quick search and I think that should work.

  • shinXdxdshinXdxd Posts: 6Member

    I tried the code with GDScript and there it works, but If I do the same in C# the whole IDE crashes as soon as I try to compile.
    var sprite = new Sprite(); is actually the same as Sprite sprite = new Sprite(); at least with this simple line of code.
    This is the output i got (I'm using linux) :

    https://pastebin.com/R7kkcV9k

  • cyberealitycybereality Posts: 1,454Moderator

    I understand what the error is staying. It looks like your Block class needs a default constructor (with no parameters/arguments). For example, try something like this:

    public class Block : StaticBody2D
    {
        private BlockType type {get;}
        // private Sprite sprite = new Sprite(); // this line causes a crash
       public Block() 
       {
       }
        public Create(BlockType type, Vector2 position)
        {
            this.type = type;
            this.Position = position;
           // crashes somewhere on the next lines
            Sprite sprite = new Sprite();
            sprite.Texture = (Texture) GD.Load("res://assets/earth.png");
            this.AddChild(sprite);
        }
    
  • cyberealitycybereality Posts: 1,454Moderator

    Also, you need to verify your account so your posts don't get stuck in the queue. Be sure to check your email.

  • shinXdxdshinXdxd Posts: 6Member

    Thank you for your help.
    I went once again through the_ Your first game_ tutorial and made it with like the mob spawning with a packed scene. Now it's working.

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file