C# indexing 2D Array from GDScript results in NullReferenceException

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

I’m making a Chess engine, but the engine is having some performance issues so I decided to transfer functions with heavy calculations from GDScript to C#. What keeps me from making proper progress is an error in C#.

Here are simplified versions of the scripts. foo.gd and Bar.cs are both AutoLoad scripts with the node name of Bar.cs as ‘Bar’.

foo.gd

extends Node

func _ready():
	var inp = [[1, 2], [3, 4]]
	print(Bar.Test(inp))

Bar.cs

using Godot;
using System;

public class Bar : Node
{
    public override void _Ready(){
    }

    public static int Test(int[,] inp){
        return inp[1, 1];
    }
}

Whenever I index 2D Array in C# and the Array originated from GDScript, Godot throws the following error:

Int32 Bar.Test(System.Int32[,] ): System.NullReferenceException: Object reference not set to an instance of an object

The error refers to line 10 of Bar.cs. When I try to input 1D Array (i.e. [1, 2, 3, 4]) from foo.gd and tweak the C# function for indexing 1D Array, it worked, but Chess boards are 2D. I also tried calling the function from Bar.cs itself and input C#-type 2D Array, and it also worked, but I need to call from foo.gd.

What fixes this bug?

:bust_in_silhouette: Reply From: juppi

In short, you have to use the Godot.Collections.Array:

public static int Test(Array<Array<int>> inp)
{
    return inp[1][1];
}

Thank you for suggesting, but a new error arises from this:

The non-generic type ‘Array’ cannot be used with type arguments

Vincent William Rodr | 2022-04-30 07:44

By replacing Array with Godot.Collections.Array, the code finally works! Thank you so much.

Here is the function

public static int Test(Godot.Collections.Array<Godot.Collections.Array<int>> inp){
    return inp[1][1];
}

Vincent William Rodr | 2022-04-30 10:12