How to create a C# int[,] array in Godot?

Godot 4.2.2

I’m trying to pass a 2D array to a C# function that requires it to be structured as int[,] rather than int. The array is randomly generated and will look something like this:
[[1, 1, 0, 1, 0, 1, 1],
[0, 1, 0, 1, 1, 1, 1],
[1, 1, 0, 1, 0, 1, 1],
[0, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 0, 1],
[1, 1, 0, 1, 1, 1, 1]]
Alternatively, if someone is able to show me a solution for using Godot’s built in AStar tools (which I have not been able to get working thus far), that would work as well. I’m using the C# code from here and outside of not being able to pass the array to it, it seems to work in an isolated environment.

I can’t pass it directly without getting the “Invalid call. Nonexistent function FunctionName” because the array supplied doesn’t count as the right kind of 2D array.

[][] #jagged array
[,] # 2d array

Just make sure your function parameter type matches your array declaration.

So how I would I go about making a 2d array rather than a jagged array in Godot?

Godot uses it’s own Array class. But while your in c# land i assume you can do anything you want.

var array = new Godot.Collections.Array{"One", 2, 3, "Four"};
GD.Print(array[0]); // One.
GD.Print(array[2]); // 3.
GD.Print(array[array.Count - 1]); // Four.
array[2] = "Three";
GD.Print(array[array.Count - 2]); // Three.

The Godot docs have c# examples

var array2D = new Godot.Collections.Array{
new Godot.Collections.Array{"One", 2, 3, "Four"},
new Godot.Collections.Array{"One", 2, 3, "Four"},
new Godot.Collections.Array{"One", 2, 3, "Four"},
}

So I assume this means I CANNOT make a 2d array in Godot, only a Jagged array? The function I’m calling from GDScript wants a 2d array specifically.

technically Jagged array can be 2D array.

As long as your 2d array is used in the c# code it should be fine. I think, i don’t use c#.

Your example code looks to use jagged array syntax with a fixed column width.

int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

You just need to change the parameters of the example function to [,] instead of [][col]

If you need to call Godot Engine functions you need to use Array.

If the function in question specifically requires a 2d array and not a jagged, Godot’s arrays will not count and result in an error.

That’s C++ code, but I’ll see about modifying it in a similar way. However, I suppose that means the answer to my original question is “cannot be done”…

2 Likes

Hm, the problem may be different from what I expected; I can’t get Godot to pass the entire array to C#, it only gives the first “row” of the array no matter what.


This is an abomination but it works.