Unity Netcode helps you make games where many players can play together over the internet. It makes sharing game data between players easy and smooth.
Unity Netcode overview
using Unity.Netcode; public class MyNetworkScript : NetworkBehaviour { public NetworkVariable<int> playerScore = new NetworkVariable<int>(0); public override void OnNetworkSpawn() { if (IsServer) { playerScore.Value = 10; } } }
NetworkBehaviour is a special class for scripts that work with Unity Netcode.
NetworkVariable is used to share data like numbers or positions between players automatically.
public NetworkVariable<int> health = new NetworkVariable<int>(100);
if (IsServer) { health.Value -= 10; }
IsOwner to run code only for the player controlling this object.public override void OnNetworkSpawn()
{
if (IsOwner)
{
// This code runs only for the player who owns this object
}
}This simple script lets the player press space to increase their score. The score is shared with all players using Unity Netcode. The server updates the score and all players see the change.
using UnityEngine; using Unity.Netcode; public class SimplePlayer : NetworkBehaviour { public NetworkVariable<int> score = new NetworkVariable<int>(0); void Update() { if (!IsOwner) return; if (Input.GetKeyDown(KeyCode.Space)) { IncreaseScoreServerRpc(); } } [ServerRpc] void IncreaseScoreServerRpc() { score.Value += 1; Debug.Log($"Score updated to {score.Value}"); } public override void OnNetworkSpawn() { score.OnValueChanged += (oldValue, newValue) => { Debug.Log($"Score changed from {oldValue} to {newValue}"); }; } }
Always run data changes on the server to keep the game fair and synced.
Use NetworkVariable for simple shared data like scores or health.
Use ServerRpc to send commands from players to the server.
Unity Netcode helps you build multiplayer games by sharing data between players easily.
Use NetworkBehaviour and NetworkVariable to sync game data.
Server controls data changes to keep the game fair and consistent.