- Network
- A
Universe of Network Games in Unity: A Guide for the Young Creator
A simple and clear guide to Unity Netcode for GameObjects that will help beginner developers take their first step into the world of network games.
Hello, future genius of game worlds!
Have you ever wondered how, in games, you can see your friend, run around with them, and fight monsters together even though they're sitting at home? That's all programming magic, and it's called Netcode.
Let's figure out how this magic works together, using the special tool Unity Netcode for GameObjects as an example. Imagine it as a set of magical walkie-talkies and tools for your game characters.
What is Unity Netcode for GameObjects?
Unity is a huge construction kit where games are made.
GameObjects are everything that exists in the game: your hero, enemies, chests, bullets, cars.
Netcode is a special language for game objects on different computers to "talk" to each other over the internet.
So, Unity Netcode for GameObjects is a set of rules and tools that helps objects in a Unity-created game communicate with each other over the network.
Main magical tools
For our game objects to learn to communicate, they must have special "parts." Let's look at the main ones.
1. Magic tag: NetworkObject
What is it? It's the very first and most important tag you have to "stick" onto your player, monster, or any other item that all players need to see.
Why is it needed? This tag tells the game: "Attention! This object is a participant in the network game. It needs to be shown to everyone!" Without this tag, your character will only be visible on your screen.
2. Magic Mirror: NetworkTransform
What is it? It's like a magic mirror that constantly keeps track of where your object is and which way it's facing.
Why is it needed? It automatically tells all players the coordinates and rotation of your character. When you run forward,
NetworkTransform
tells everyone: "Hero Vasya ran forward!" And everyone sees on their screens how your hero runs. This is the simplest way to synchronize movement.
3. Shared Noticeboard: NetworkVariable
What is it? Imagine a magic noticeboard where you can write something important, and all the players will see it. For example, the amount of health, points, or the color of your character.
Why is it needed? If you pick up a coin and your score becomes 10, the game writes "10" into this variable. And all the other players immediately see: "Ah, they have 10 points!"
NetworkVariable
is shared memory for everyone.
Example code with NetworkVariable
Let's imagine our player has health.
// Connect the Netcode library
using Unity.Netcode;
using UnityEngine;
public class PlayerStats : NetworkBehaviour
{
// Create a "network variable" for health.
// It will store an integer and be visible to everyone (ReadPermission.Everyone).
// The initial value is 100.
public NetworkVariable health = new NetworkVariable(100, NetworkVariableReadPermission.Everyone);
// This function is called when our player spawns in the networked game
public override void OnNetworkSpawn()
{
// We "subscribe" to changes.
// If the value of health changes, the game will call our OnHealthChanged function.
health.OnValueChanged += OnHealthChanged;
}
// This function will be called automatically when health changes
private void OnHealthChanged(int previousValue, int newValue)
{
Debug.Log($"Player {OwnerClientId}'s health changed from {previousValue} to {newValue}");
// You can add a damage effect or update the health bar on the screen here.
}
// When the object is removed from the network, you need to unsubscribe from events
public override void OnNetworkDespawn()
{
health.OnValueChanged -= OnHealthChanged;
}
}
What happens in the code?
public NetworkVariable
— we create a special network variablehealth = ... health
where health is stored. All players can see its value.health.OnValueChanged += OnHealthChanged;
— we tell the game: "When the value ofhealth
changes, please run the code in theOnHealthChanged
function."OnHealthChanged(...)
— in this function, we can write logic that should trigger when health changes. For example, print a message to the console or update the UI.
4. Loud Yell to the Boss: ServerRpc (Call on the Server)
What is this? In networked games, there is a "boss" — the server. It keeps things in order and makes important decisions.
ServerRpc
is like your character yelling loudly at the server: "Hey boss, I want to do something!"Why do it? For important actions that need to be fair for everyone. For example, you want to open a chest. You can’t do this alone (someone else might get there first). You send a
ServerRpc
request to the server: "Please open this chest!" The server checks if it’s possible and, if yes, opens it for everyone. This protects the game from cheating.
Code Example with ServerRpc
The player wants to change their color and asks the server to do it.
// Connect the Netcode library
using Unity.Netcode;
using UnityEngine;
public class PlayerActions : NetworkBehaviour
{
// This variable will store the color and synchronize it among everyone
public NetworkVariable playerColor = new NetworkVariable(Color.white);
private MeshRenderer _meshRenderer;
void Awake()
{
// Find the component once and "remember" it
_meshRenderer = GetComponent();
}
void Update()
{
// Check if this is our own character that we're controlling
if (!IsOwner)
{
return;
}
// If we pressed the "R" key
if (Input.GetKeyDown(KeyCode.R))
{
// We call a function that will send a request to the server
RequestRandomColorServerRpc();
}
}
// This special attribute says the function runs on the SERVER
[ServerRpc]
private void RequestRandomColorServerRpc()
{
// This code will run on the server!
// The server generates a random color and sets it in the network variable
Color randomColor = new Color(Random.value, Random.value, Random.value);
playerColor.Value = randomColor;
}
// This function will continuously update the model's color for all players
void LateUpdate()
{
// Use the already found component
_meshRenderer.material.color = playerColor.Value;
}
}
What happens in the code?
if (Input.GetKeyDown(KeyCode.R))
— The player presses a key.RequestRandomColorServerRpc();
— The player calls a function with the[ServerRpc]
attribute. But in reality, this command "flies" over the network to the server.[ServerRpc] private void RequestRandomColorServerRpc()
— The server receives the command and executes the code inside this function: it generates a random color and puts it in the network variableplayerColor.Value
.Since
playerColor
is aNetworkVariable
, all other players immediately learn about the new color, and theirLateUpdate
recolors the necessary model.
5. Announcement from the Boss: ClientRpc (Call on Clients)
What is it? This is when the server, on the contrary, wants to announce something to all players (called clients). For example: "Attention! A storm will begin in 10 seconds!" or "Game over! The blue team won!".
Why is it needed? So all players simultaneously learn about an important event the server decided to trigger. This allows you to synchronize effects, sounds, and events on all computers.
Example code with ClientRpc
The server has decided that the game is over and announces this to everyone.
// Connect the Netcode library
using Unity.Netcode;
using UnityEngine;
public class GameEvents : NetworkBehaviour
{
// Let's imagine the server calls this function when the game ends
public void EndGame()
{
// Only the server can make such announcements
if (!IsServer) return;
// The server calls a function that "flies" to all clients
AnnounceWinnerClientRpc("Red Team");
}
// This special attribute says the function runs on EVERY CLIENT
[ClientRpc]
private void AnnounceWinnerClientRpc(string winnerName)
{
// This code will run on every player's computer!
Debug.Log($"Game over! Winner: {winnerName}");
// Here you can show a nice victory screen
}
}
What happens in the code?
The server, for some reason, decides to end the game and calls
EndGame()
.Inside, it calls the function
AnnounceWinnerClientRpc("Red Team")
with the[ClientRpc]
tag.This command goes out to all connected players.
On each player's computer, the code from
AnnounceWinnerClientRpc
runs, and everyone sees the message about the winner.
How do you put it all together?
Imagine a simple player who can move and change color.
You create a player object in Unity.
You add a
NetworkObject
component to make it networked.You add
NetworkTransform
so that its movement is automatically synchronized.You write a script similar to
PlayerActions
from the example above. In it:In the
Update
function, you checkif (IsOwner)
and read key presses (W, A, S, D) to move the character. Because it has aNetworkTransform
, its position will automatically sync to other players.You also check for another key press (for example, "R") and call a
ServerRpc
to ask the server to change your color.The server changes the color in a
NetworkVariable
.All players see the color change because
NetworkVariable
is shared by everyone.
Step by step, using these magical tools, you can create your own worlds to invite friends into!
Write comment