MessageBase with custom member variable
I'm having trouble with a custom message base.
It's very simple:
public class CustomUpdate : MessageBase {
public CustomClass object;
}
CustomClass looks as follows:
public class CustomClass {
public string id;
public List<int> clients;
}
However, I'm getting multiple errors here. I'm quite sure it has something to do with the List<int>
, cause I don't get any errors, when I uncomment that property.
The error messages are
UNetWeaver error: GenerateSerialization for CustomUpdate unknown type [CustomClass/CustomClass]. UNet [MessageBase] member variables must be basic types.
and
UNetWeaver error: WriteReadFunc for clients [System.Collections.Generic.List '1<System.Int32>/System.Collections.Generic.List'1<System.Int32>]. Cannot have generic parameters.
Any idea how to fix this error?
Answer by AntonQvarfordt · Apr 17, 2017 at 06:57 AM
@Martinomat This isn't really my area (I'm working on learning it atm aswell) so I can't tell you how to solve the problem, but I can tell you why it doesn't work..
MessageBase/Reader/Writer doesn't support lists. To see what it supports check out the public functions here: https://docs.unity3d.com/ScriptReference/Networking.NetworkReader.html
You can probably turn a list or at least an array into Bytes or something like that and pack/unpack that conversion in Write/Read. Maybe that gives you an idea of what to search for, at least.
EDIT: I ended up needing the same solution you needed so I'll post my findings here. I'm posting two methods, one turns a list of ints into a string, the other turns a string into a list of ints. So replace the List clients with a string clients and use these functions to convert to and from.
public string WriteToString(List<int> intList)
{
StringBuilder sb = new StringBuilder("");
foreach (int i in intList)
{
sb.Append(i + "_");
}
return = sb.ToString();
}
public List<int> ReadToIntList(string str)
{
var returnValue = new List<int>();
var splitIntList = str.Split('_');
foreach (var intString in splitIntList)
{
returnValue.Add(int.Parse(intString));
}
return returnValue;
}
There is probs a more efficient way to do it, but this works fine.