Skip to main content

[Server]

The [Server] attribute designates that the method can only be executed on the server.

Key Features

  • Executes only on the server.
  • A warning is triggered if called from the client.
  • Can be used in both Unity's game loop methods (like Start, Update, etc.) and regular methods.
  • If used in overridden methods, the attribute must also be specified in the overridden method.

Use Examples

Basic Use

public class GameManager : NetworkBehaviour
{
[Server]
void Update()
{
// Logic that runs only on the server
// Example: Game state updates
UpdateGameState();
}

[Server]
private void UpdateGameState()
{
// Game state update logic
// Notify clients via ClientRpc if necessary
}
}

Using in Inherited Methods

public abstract class BaseEnemy : NetworkBehaviour
{
[Server]
protected virtual void HandleAI()
{
// Basic AI logic
}
}

public class SpecificEnemy : BaseEnemy
{
[Server]
protected override void HandleAI()
{
base.HandleAI();
// Additional AI logic
}
}

Using with State Checks

public class SpawnManager : NetworkBehaviour
{
[Server]
private void SpawnEnemy()
{
// Server check
if (!isServer)
{
Debug.LogWarning("Enemy spawning is only allowed on the server");
return;
}

// Enemy spawning logic
GameObject enemy = Instantiate(enemyPrefab);
NetworkServer.Spawn(enemy);
}
}
note
  1. Methods with the [Server] attribute should include logic that must be executed only on the server.
  2. To pass information to the client, you should use [ClientRpc].
  3. Typical use cases include AI handling, game logic processing, and object spawning. :::