Multiplayer (co-op)
One player hosts and up to three more join. The host's machine runs the world — AI, physics, loot, building, the clock — and everyone else sees it. Each player moves their own character, so their controls feel instant. Over Steam, friends join by invite with no ports to open. On one PC or a LAN, the ENet transport joins by IP address.
Setting up a scene
- Make the player a prefab (character controller, mesh, camera as a child, scripts). Give its root a Net Identity.
- Add a Network Manager to an entity in the scene and point Player prefab at it. Players appear at that entity, side by side.
- Do not also place a player in the scene. The host spawns one for every player, itself included, and once when playing alone.
- Give a Net Identity to anything that moves or changes and must look the same for everyone: animals, doors, dropped items. Static scenery does not need one.
Who runs what
| Owner | The machine that simulates an entity: the host for the world, the player for their own character. |
| Copy | Everyone else's version. It follows what the owner sends (positions ~20 times a second, drawn ~100 ms behind so it moves smoothly). Its physics is kinematic, its character controller is not simulated, its camera is off. |
| Scripts | A networked entity's scripts run only on its owner (Net Identity: Scripts only on the owner). So an animal's AI runs once, on the host. Behaviour trees and navigation follow the same rule. |
| Scene | The host decides. A joining player loads the host's scene, and a host changing scene takes everyone with it. |
Scripting
class Tree : public Thread::ScriptableEntity {
float m_Health = 100.0f;
// The host keeps this in step on every client.
void DeclareReplicated(Replicated& r) override { r.Float("Health", m_Health); }
// What other machines may call on this script.
void DeclareRpcs(RpcTable& r) override { r.On("Chop", &Tree::RpcChop); }
void OnInteract(Entity player) {
CallHost("Chop", 25.0f, player); // a client asks; on the host it runs right here
}
void RpcChop(RpcCall& c) { // runs on the host
float dmg = c.Float(); Entity who = c.GetEntity();
if (!c.Ok() || !IsAuthority()) return;
m_Health -= dmg;
if (m_Health <= 0) Thread::NetReplication::Despawn(Self()); // gone for everyone
}
};
| IsAuthority() | This machine decides the world (the host, or alone). Gate damage, loot and spawning on it. |
| IsLocallyOwned() | This machine simulates this entity. Gate reading the keyboard on it, so one player's keys never steer another's character. |
| IsHost() / IsClient() / IsOnline() | The session itself. |
| LocalPlayer() / LocalPeer() | This machine's character and player id. Use instead of FindByName("Player"), which finds a player, not yours. |
| CallHost / CallAll / CallOwner | Run one of this script's RPCs on the host, on everyone (host only), or on the entity's owner (host only). Arguments: float, int, bool, string, Vec3, Entity. Read them back in the same order through RpcCall. A wrong type gives defaults and Ok() == false. |
| DeclareReplicated | Values the host sends to every client when they change (and in full to a player who joins later). A client asks for a change by RPC. |
| NetReplication::Spawn / Despawn | Host only: create or destroy an entity on every machine. Spawned prefabs get the same uuids everywhere. |
IsLocallyOwned() for input and
IsAuthority() for state.Joining a game in progress
A player who joins late gets the world as it is. That is everything tagged Persistent that was built, felled or moved (the same difference a save holds), then the live spawns (other players, creatures), then the current replicated values.
Saving
Only the host saves. The world uses WorldState as in single player. Each player's
character is the game's to store, keyed by NetReplication::PlayerKeyOf(peer):
steam:<id> over Steam, so the same person gets the same character back.
Steam
- Project Settings › Steam App ID. 480 is Valve's test app; use it until the game has its own.
- Build the game. It carries
steam_api64.dlland asteam_appid.txt, starts Steam, and names players after their accounts. - Host:
Steam::HostGame(4), or a UI button with Actionsteam.host. This opens a friends-only lobby. - Invite:
Steam::InviteFriends()or Actionsteam.inviteopens the overlay. - Accepting an invite joins automatically, also when Steam starts the game with
+connect_lobby. Actionnet.leaveleaves.
A real Steam connection needs two accounts on two machines.
Hosting from a menu: net.host
A UI button with Action net.host hosts the way Project Settings › Multiplayer says:
- Auto (default): over Steam when it is running, otherwise over ENet. One menu then works in a Steam build and in a plain one.
- Steam only: without Steam it does not host and logs why.
- ENet (IP) only: players join with
--connect <ip>:<port>, and the host forwards that UDP port.
The same section sets the ENet port (also what --host without a number uses) and the player limit (1–4).
Testing on one PC
- Build the project once (the client is the built game).
- Save the scene. Joining players load the file, not what is on screen.
- Play dropdown › Multiplayer › Host a game, then Play.
- Play dropdown › Launch a client (last build). It starts the game with
--connect 127.0.0.1:27015.
Stop ends the session. A built game also accepts --host [port],
--connect host:port and --name <name>. Over MCP:
net_status, net_host, net_join, net_leave.
Dedicated server
The built game is also its own server: no window, no graphics device, no sound, a console on stdin. The machine hosts but does not play — it gets no character, and everyone connects to it.
Game.exe --server 27015 --scene assets/scenes/main.thread --max-players 8
Or let the build write it: Build Settings › Dedicated server › Write dedicated
server files, with port, player limit, world scene and name. A Windows build then carries
StartServer.bat, a Linux build start-server.sh and a systemd unit
(thread-server.service), both with SERVER.txt.
--server [port]— host over ENet (UDP, default 27015). Forward that port.--scene <path>— the world to load. Needed: a game's start scene is usually a splash and a menu that nobody is there to click.--max-players <n>— people who may connect (default 4); the server is not one of them.--name <name>— how the server appears in the chat (default Server).
Console: status, kick <id|name> [reason] (the player is told why and does
not reconnect), say <text>, save, quit. Ctrl+C and SIGTERM stop it
the same way as quit. Output stays on the console (no game.log).
Saving is the game's: save and quit invoke the UI action game.save
if the game binds one (UIActions::Bind("game.save", ...)); otherwise only the game's own
autosave writes anything. A game that wants its last save back when the server starts loads it
itself. Clients join with --connect host:port; Steam is not used by the server.
Limits today
- Up to 4 players by default, host-authoritative. A dedicated server runs over ENet only (no Steam relay, no server browser).
- Positions and rotations are replicated; animation follows from the scripts on each machine.
- Host and clients must run the same build (refused otherwise, with the reason).
See also
NetIdentityComponent · NetworkManagerComponent · ScriptableEntity · PersistentComponent
Multiplayer (co-op)
Jeden gracz hostuje, a do trzech kolejnych dołącza. Komputer hosta prowadzi świat (AI, fizykę, łupy, budowanie, czas), a pozostali go oglądają. Każdy gracz porusza własną postacią, więc sterowanie reaguje od razu. Przez Steam znajomi dołączają z zaproszenia, bez otwierania portów. Na jednym komputerze albo w LAN-ie transport ENet łączy po adresie IP.
Przygotowanie sceny
- Zrób z gracza prefab (kontroler postaci, mesh, kamera jako dziecko, skrypty). Na jego korzeń dodaj Net Identity.
- Dodaj Network Manager do jakiejś encji w scenie i ustaw w nim Player prefab. Gracze pojawią się przy tej encji, obok siebie.
- Nie wstawiaj dodatkowo gracza do sceny. Host spawnuje go każdemu, sobie też, i raz przy grze solo.
- Net Identity daj wszystkiemu, co się rusza albo zmienia i u każdego ma wyglądać tak samo: zwierzętom, drzwiom, upuszczonym przedmiotom. Statyczna sceneria go nie potrzebuje.
Kto co liczy
| Właściciel | Komputer, który symuluje encję: host dla świata, gracz dla własnej postaci. |
| Kopia | Wersja u pozostałych. Podąża za tym, co wysyła właściciel (pozycje ok. 20 razy na sekundę, rysowane ok. 100 ms wstecz, więc ruch jest płynny). Fizyka kopii jest kinematyczna, jej kontroler postaci nie jest symulowany, a kamera jest wyłączona. |
| Skrypty | Skrypty encji sieciowej działają tylko u jej właściciela (Net Identity: Scripts only on the owner). AI zwierzęcia liczy się więc raz, u hosta. Drzewa zachowań i nawigacja działają tak samo. |
| Scena | Decyduje host. Dołączający wczytuje scenę hosta, a gdy host zmienia scenę, wszyscy idą za nim. |
Skrypty
class Tree : public Thread::ScriptableEntity {
float m_Health = 100.0f;
// Host trzyma tę wartość w zgodzie u każdego klienta.
void DeclareReplicated(Replicated& r) override { r.Float("Health", m_Health); }
// Co inne komputery mogą wywołać w tym skrypcie.
void DeclareRpcs(RpcTable& r) override { r.On("Chop", &Tree::RpcChop); }
void OnInteract(Entity player) {
CallHost("Chop", 25.0f, player); // klient prosi; u hosta wykona się od razu tutaj
}
void RpcChop(RpcCall& c) { // wykonuje się u hosta
float dmg = c.Float(); Entity who = c.GetEntity();
if (!c.Ok() || !IsAuthority()) return;
m_Health -= dmg;
if (m_Health <= 0) Thread::NetReplication::Despawn(Self()); // znika u wszystkich
}
};
| IsAuthority() | Ten komputer decyduje o świecie (host albo gra solo). Od tego uzależnij obrażenia, łupy i spawnowanie. |
| IsLocallyOwned() | Ten komputer symuluje tę encję. Od tego uzależnij czytanie klawiatury, żeby klawisze jednego gracza nie sterowały cudzą postacią. |
| IsHost() / IsClient() / IsOnline() | Stan samej sesji. |
| LocalPlayer() / LocalPeer() | Postać i numer gracza tego komputera. Używaj zamiast FindByName("Player"), które znajduje jakiegoś gracza, niekoniecznie twojego. |
| CallHost / CallAll / CallOwner | Uruchamia RPC tego skryptu u hosta, u wszystkich (tylko host) albo u właściciela encji (tylko host). Argumenty: float, int, bool, string, Vec3, Entity. Odczytujesz je w tej samej kolejności przez RpcCall. Zły typ daje wartości domyślne i Ok() == false. |
| DeclareReplicated | Wartości, które host wysyła klientom przy każdej zmianie (a w całości graczowi, który dołącza później). Klient prosi o zmianę przez RPC. |
| NetReplication::Spawn / Despawn | Tylko host: tworzy albo niszczy encję na wszystkich komputerach. Spawnowane prefaby mają wszędzie te same UUID. |
IsLocallyOwned() przy sterowaniu i
IsAuthority() przy stanie.Dołączanie do trwającej gry
Gracz dołączający później dostaje świat taki, jaki jest. Najpierw idzie wszystko oznaczone jako Persistent, co zbudowano, ścięto albo przesunięto (ta sama różnica, którą trzyma zapis), potem bieżące spawny (inni gracze, stworzenia), a na końcu aktualne wartości replikowane.
Zapis
Zapisuje tylko host. Świat idzie przez WorldState, tak jak w grze solo. Postacie
graczy zapisuje gra pod kluczem NetReplication::PlayerKeyOf(peer): przez Steam to
steam:<id>, więc ta sama osoba dostaje z powrotem swoją postać.
Steam
- Project Settings › Steam App ID. 480 to testowa aplikacja Valve; używaj jej, dopóki gra nie ma własnej.
- Zbuduj grę. Dostanie
steam_api64.dllisteam_appid.txt, sama uruchomi Steam, a graczy nazwie ich nickami ze Steama. - Hostowanie:
Steam::HostGame(4)albo przycisk UI z akcjąsteam.host. Tworzy lobby tylko dla znajomych. - Zaproszenie:
Steam::InviteFriends()albo akcjasteam.inviteotwiera overlay. - Przyjęcie zaproszenia dołącza samo, także gdy Steam uruchamia grę z
+connect_lobby. Akcjanet.leavewychodzi z gry.
Prawdziwe połączenie przez Steam wymaga dwóch kont na dwóch komputerach.
Hostowanie z menu: net.host
Przycisk UI z akcją net.host hostuje tak, jak mówi Project Settings › Multiplayer:
- Auto (domyślnie): przez Steam, gdy działa, w przeciwnym razie przez ENet. To samo menu działa wtedy w buildzie ze Steamem i bez niego.
- Steam only: bez Steama nie hostuje i zapisuje w logu dlaczego.
- ENet (IP) only: gracze dołączają przez
--connect <ip>:<port>, a host przekierowuje ten port UDP.
Ta sama sekcja ustawia port ENet (także dla --host bez numeru) i limit graczy (1–4).
Testowanie na jednym komputerze
- Zbuduj raz projekt (klientem jest zbudowana gra).
- Zapisz scenę. Dołączający wczytują plik, a nie to, co masz na ekranie.
- Menu Play › Multiplayer › Host a game, potem Play.
- Menu Play › Launch a client (last build). Uruchamia grę z
--connect 127.0.0.1:27015.
Stop kończy sesję. Zbudowana gra przyjmuje też --host [port],
--connect host:port i --name <nick>. Przez MCP:
net_status, net_host, net_join, net_leave.
Serwer dedykowany
Zbudowana gra jest też swoim serwerem: bez okna, bez karty graficznej, bez dźwięku, z konsolą na standardowym wejściu. Komputer hostuje, ale nie gra — nie dostaje postaci, a wszyscy łączą się do niego.
Game.exe --server 27015 --scene assets/scenes/main.thread --max-players 8
Albo niech zapisze to build: Build Settings › Dedicated server › Write dedicated
server files, z portem, limitem graczy, sceną świata i nazwą. Build na Windowsa dostaje wtedy
StartServer.bat, build na Linuksa start-server.sh i usługę systemd
(thread-server.service), oba z SERVER.txt.
--server [port]— hostowanie przez ENet (UDP, domyślnie 27015). Ten port trzeba przekierować.--scene <ścieżka>— świat do wczytania. Potrzebne: scena startowa gry to zwykle splash i menu, w które nikt nie kliknie.--max-players <n>— ilu ludzi może się podłączyć (domyślnie 4); serwer się nie wlicza.--name <nazwa>— jak serwer podpisuje się na czacie (domyślnie Server).
Konsola: status, kick <id|nick> [powód] (gracz dostaje powód i nie łączy się
ponownie), say <tekst>, save, quit. Ctrl+C i SIGTERM zatrzymują serwer
tak samo jak quit. Wyjście zostaje na konsoli (bez game.log).
Zapis należy do gry: save i quit wywołują akcję UI game.save, jeśli gra
ją podpina (UIActions::Bind("game.save", ...)); inaczej zapisuje tylko własny autozapis gry.
Gra, która chce wczytać ostatni zapis przy starcie serwera, robi to sama. Klienci dołączają przez
--connect host:port; serwer nie używa Steama.
Ograniczenia na dziś
- Domyślnie do 4 graczy, autorytet hosta. Serwer dedykowany działa tylko przez ENet (bez przekaźników Steama i bez listy serwerów).
- Replikowane są pozycje i obroty; animacja wynika ze skryptów na każdym komputerze.
- Host i klienci muszą mieć ten sam build (inaczej odmowa z podanym powodem).
Zobacz też
NetIdentityComponent · NetworkManagerComponent · ScriptableEntity · PersistentComponent