Networking Command class argument
I'm trying to implement some kind of Flux architecture in Unity. Now I want to use it in multiplayer game. The idea is to send action to the server and then the server will distribute it to the clients.
I wanted to use Command in order to send the Action to the server:
[Command]
public void CmdDispatch(Action action) {
// handle action
}
However when I run this code I got some kind of strange error.
InvalidProgramException: Invalid IL code in Unity.GeneratedNetworkCode:_ReadAction_None (UnityEngine.Networking.NetworkReader): IL_0000: newobj 0x06000001
After some investigation, I find out that the problem is the Action argument. The Action class looks like this
public class Action
{
private string type;
private Dictionary<string, object> data;
// constructor and some methods
}
I think I need to serialize the Action object somehow. So the question is how to do that and if Command is a good approach for this or I should rather use something else.
Answer by js__ · Mar 22, 2016 at 07:06 PM
I managed to resolve this problem, so I think it is a good idea to put here solution in case somebody with similar problem found this.
First of all I serialized the Action object itself to byte array. I found this answer on Stack Overflow useful.
However, serialized Action object was too large due to the Dictionary. So I created structure where I converted Dictionary to 2 arrays.
[Serializable]
public struct ActionStruct
{
public string type;
public string[] keys;
public object[] values;
}
This was about 10 times smaller than the original action which was fine to send as an Command argument.
Answer by softrare · Mar 21, 2016 at 12:00 PM
A command cannot be executed with any arbitrary object as parameter.
Read here: http://docs.unity3d.com/Manual/UNetActions.html
"Arguments to Remote Actions
The arguments passed to commands and ClientRpc calls are serialized and sent over the network. These arguments can be:
basic types (byte, int, float, string, UInt64, etc)
arrays of basic types
structs containing allowable types
built-in unity math types (Vector3, Quaternion, etc)
NetworkIdentity
NetworkInstanceId
NetworkHash128
GameObject with a NetworkIdentity component attached"
EDIT: Oh didn't read the end of your question. Ok, to do what you want you will have to send data over to the server in one of the above datatypes and create the Action object on the "other side" (on the server).
Your answer
Follow this Question
Related Questions
MultipartFormDataSection not working - Error: 403 0 Answers
ClientRpc not functioning 0 Answers
Unity Networking 0 Answers
Check what group id you have after being instantiated. (PUN) 1 Answer