0
0
Unityframework~7 mins

Unity Netcode overview

Choose your learning style9 modes available
Introduction

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.

You want to create a multiplayer game where players can see and interact with each other.
You need to sync player movements and actions in real-time across different devices.
You want to manage game events like scoring or health changes for all players at once.
You want to build a cooperative or competitive game that works online.
You want to handle player connections and disconnections smoothly.
Syntax
Unity
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.

Examples
This creates a shared health value starting at 100 that all players can see.
Unity
public NetworkVariable<int> health = new NetworkVariable<int>(100);
Only the server can change the health value to keep data consistent.
Unity
if (IsServer)
{
    health.Value -= 10;
}
Use IsOwner to run code only for the player controlling this object.
Unity
public override void OnNetworkSpawn()
{
    if (IsOwner)
    {
        // This code runs only for the player who owns this object
    }
}
Sample Program

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.

Unity
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}");
        };
    }
}
OutputSuccess
Important Notes

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.

Summary

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.