#Custom reader/writer for dictionnaries

2 messages · Page 1 of 1 (latest)

wicked apex
#

I made a custom serializer/deserializer for a dictionary<netId, List<Task>> storing the tasks for every players.

public static void WriteMyPlayerTasks(this NetworkWriter writer, Dictionary<uint, List<Task>> playersTasks)
{
    writer.Write((uint)playersTasks.Count);
    foreach(KeyValuePair<uint, List<Task>> playerTasks in playersTasks)
    {
        writer.Write(playerTasks.Key);
        writer.WriteList<Task>(playerTasks.Value);
    }
}

public static Dictionary<uint, List<Task>> ReadMyPlayerTasks(this NetworkReader reader)
{
    Dictionary<uint, List<Task>> playersTasks = new Dictionary<uint, List<Task>>();
    uint playersCount = reader.ReadUInt();
    for(int i = 0; i < playersCount; i++)
    {
        playersTasks.Add(reader.ReadUInt(), reader.ReadList<Task>());
    }

    return playersTasks;
}

This code above works ✅
Then I wanted to simplify it creating a custom reader/writer for dictionaries like so :

public static void WriteMyDictionary<TKey, TValue>(this NetworkWriter writer, Dictionary<TKey, TValue> dictionary)
{
    writer.WriteUInt((uint)dictionary.Count);

    foreach (KeyValuePair<TKey, TValue> item in dictionary)
    {
        writer.Write(item.Key);
        writer.Write(item.Value);
    }
}

public static Dictionary<TKey, TValue> ReadMyDictionary<TKey, TValue>(this NetworkReader reader)
{
    Dictionary<TKey, TValue> returnValue = new Dictionary<TKey, TValue>();
    uint count = reader.ReadUInt();
    for (uint i = 0; i < count; i++)
    {
        returnValue.Add(
            reader.Read<TKey>(),
            reader.Read<TValue>()
        );
    }
    return returnValue;
}

But it doesn't work with that code anymore...

#

I did this and then the editor started crashing :

    public static void WriteMyPlayerTasks(this NetworkWriter writer, Dictionary<uint, List<Task>> playersTasks) => writer.Write(playersTasks);
    public static Dictionary<uint, List<Task>> ReadMyPlayerTasks(this NetworkReader reader) => reader.Read<Dictionary<uint, List<Task>>>();

I have working reader/writers for the Task class

I'd like to find a way that wouldn't require to make serializer for dictionnaries of every TKey TValue combination.