[Command]
[Command]
attribute is used when a client needs to call a function on the server. It allows a client to request the server to execute a function.
Key Features
- Can only be called from the client to the server.
- Executed on the server.
- The function name must begin with the
Cmd
prefix. - Automatically includes the connection information of the client that called the function.
Use Examples
Basic Use
public class PlayerController : NetworkBehaviour
{
[Client]
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
CmdRequestJump();
}
}
[Command]
private void CmdRequestJump()
{
// Jump logic executed on the server
// Physics processing, position changes, etc.
}
}
Passing Parameters
public class PlayerCombat : NetworkBehaviour
{
[Client]
private void OnFireButtonPressed(Vector3 targetPosition)
{
CmdFireWeapon(targetPosition);
}
[Command]
private void CmdFireWeapon(Vector3 targetPosition)
{
// Shooting logic executed on the server
// Bullet creation, collision handling, etc.
}
}
Authentication Check
public class PlayerInventory : NetworkBehaviour
{
[Command]
private void CmdUseItem(int itemId)
{
// Check if the client owns the item
if (!isOwned)
return;
// Check if the item can be used
if (!HasItem(itemId))
return;
// Item use logic
UseItemOnServer(itemId);
}
}
note
- The [Command] attribute is used to safely process client requests on the server.
- The function name must always start with
Cmd
to ensure it is correctly recognized as a command. - It is primarily used to pass player actions such as input handling, item usage, or attacks from the client to the server. :::