Class CommandAttribute
This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on the server by sending a command from a client.
[Command] functions are invoked on the player GameObject associated with a connection. This is set up in response to the "ready" message, by passing the player GameObject to the NetworkServer.PlayerIsReady() function. The arguments to the command call are serialized across the network, so that the server function is invoked with the same values as the function on the client. These functions must begin with the prefix "Cmd" and cannot be static.
using UnityEngine;
using UnityEngine.Networking;
public class Player : NetworkBehaviour
{
int moveX = 0;
int moveY = 0;
float moveSpeed = 0.2f;
bool isDirty = false;
void Update()
{
if (!isLocalPlayer)
{
return;
}
// input handling for local player only
int oldMoveX = moveX;
int oldMoveY = moveY;
moveX = 0;
moveY = 0;
if (Input.GetKey(KeyCode.LeftArrow))
{
moveX -= 1;
}
if (Input.GetKey(KeyCode.RightArrow))
{
moveX += 1;
}
if (Input.GetKey(KeyCode.UpArrow))
{
moveY += 1;
}
if (Input.GetKey(KeyCode.DownArrow))
{
moveY -= 1;
}
if (moveX != oldMoveX || moveY != oldMoveY)
{
CmdMove(moveX, moveY);
}
}
[Command]
public void CmdMove(int x, int y)
{
moveX = x;
moveY = y;
isDirty = true;
}
public void FixedUpdate()
{
if (NetworkServer.active)
{
transform.Translate(moveX * moveSpeed, moveY * moveSpeed, 0);
}
}
}
The allowed argument types are;
- Basic type (byte, int, float, string, UInt64, etc)
- Built-in Unity math type (Vector3, Quaternion, etc),
- Arrays of basic types
- Structs containing allowable types
- NetworkIdentity
- NetworkInstanceId
- NetworkHash128
- GameObject with a NetworkIdentity component attached.
Namespace: UnityEngine.Networking
Syntax
[AttributeUsage(AttributeTargets.Method)]
[Obsolete("The high level API classes are deprecated and will be removed in the future.")]
public class CommandAttribute : Attribute, _Attribute
Fields
channel
The QoS channel to use to send this command on, see QosTypeQosType.
Declaration
public int channel
Field Value
Type | Description |
---|---|
Int32 |