While it is fairly easy to exchange simple types like strings or integers between a C# and a GDScript it seems to be hard to archive the same thing for complex types.
I have written the network communication on the client (GoDot) side in C#, because there are already a variety of nuget packages available, which allows making good progress. But now comes the point where I want to connect the data retrieved via some C# code with game logic written in GDScript.
A quick example of code class relation I mean:
public class ItemDTO
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class WearableItemDTO: ItemDTO
{
public int Power { get; set; }
public int LifePoints { get; set; }
}
public class ConsumableItemDTO: ItemDTO
{
// Just some random example properties
public int duration { get; set; }
public int LifePerSeconds { get; set; }
}
public class PlayerDTO {
public Guid Id { get; set; }
public List<ItemDTO> Inventory { get; set; }
}
Sample mapping to a Dictionary:
private Dictionary ConvertPlayerToGodotDictionary(PlayerDTO player)
{
var dict = new Dictionary();
dict["id"] = player.Id.ToString();
var arr = new Array();
if (player.Inventory != null)
{
foreach (var item in player.Inventory)
{
arr.Add(ConvertItemToGodotDictionary(item));
}
}
dict["inventory"] = arr;
return dict;
}
private Dictionary ConvertItemToGodotDictionary(ItemDTO item)
{
var d = new Dictionary();
d["type"] = item.GetType().Name;
d["id"] = item.Id.ToString();
d["name"] = item.Name;
if (item is WearableItemDTO w)
{
d["power"] = w.Power;
d["life_points"] = w.LifePoints;
}
else if (item is ConsumableItemDTO c)
{
d["duration"] = c.duration;
d["life_per_seconds"] = c.LifePerSeconds;
}
return d;
}
It seems that I have two options here: Either I have to write completely new classes including mapping logic between the DTOs and some C#, that are compatible to be used in GDScript. Or, I can use untyped nested Dictionaries and Lists. Both options aren't appealing nor easy to come by with. Is there another or easier solution to share data in the structure shown above?