docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Manage connections

    Start a session, respond to connection events, and inspect connections using the static Netcode class.

    The Netcode class is the entry point for GhostObject connection management. It creates the client and server worlds you need, opens and closes connections, and reports connection events.

    For a complete example, refer to the connection sample in the Assets/GameObjectSample/0_Basics/4_Connection folder of the Netcode samples project. It starts each role from a menu.

    Note

    Everything on this page is a convenience over the entity-based connection API rather than a replacement for it. If your project already creates worlds and connects with its own code, that code keeps working, and you can adopt these APIs gradually or not at all. For more information, refer to Connecting server and clients.

    Start a session

    Call the method for the role you want.

    Method Role
    Netcode.Connect(endpoint) Connects a client to a server, and returns the Connection.
    Netcode.Listen(endpoint) Starts a server listening for connections. Returns false if it can't listen, for example when the port is in use.
    Netcode.StartAsHost(endpoint) Starts a server with a local client, and returns the local Connection.

    Build the endpoint with NetworkEndpoint:

    // Listen on all interfaces.
    Netcode.Listen(NetworkEndpoint.AnyIpv4.WithPort(7979));
    
    // Connect to a specific address.
    Netcode.Connect(NetworkEndpoint.Parse("127.0.0.1", 7979));
    

    Netcode.StartAsHost starts a host, where both client and server logic execute on the same ghosts. GhostObjects support single world host mode only. Binary-worlds mode (NetcodeConfig.HostWorldMode.BinaryWorlds) where you get both client and server ghosts in the same process also exists, but isn't supported for GhostObjects. For more information, refer to Client-hosted.

    To change connection timeouts, set Connect Timeout MS and Max Connect Attempts on the NetcodeConfig asset selected in Edit > Project Settings > Multiplayer. To connect through Unity Relay, or to change how Netcode creates its network drivers, assign your own INetworkStreamDriverConstructor to NetworkStreamReceiveSystem.DriverConstructor before you call these methods. For more information, refer to Connect using a relay server.

    You can also use the Sessions SDK to configure this.

    Connect automatically in the Editor

    You don't always have to start a session yourself. By default, when you enter Play mode, Netcode starts the role set in Play Mode Type and connects it on port 7979. A client connects to the local address 127.0.0.1. Automatic connection therefore suits local iteration on one machine, and saves you writing a connection menu.

    Two windows set Play Mode Type. Netcode provides its own Play Mode Tools window, and the separate Multiplayer Play Mode package adds a Multiplayer Play Mode window that can drive it. For more information, refer to PlayMode Tool.

    When you use the Multiplayer Play Mode window, set the role of each virtual player to tell the automatic connection process which role that player takes.

    If you start from an offline main menu, you can disable automatic connection by setting Enable Client Server Bootstrap to Disable Automatic Bootstrap on your NetcodeConfig asset. To choose per scene, add the Override Automatic Netcode Bootstrap component to a root GameObject in that scene, and set Force Automatic Bootstrap In Scene to Disable Automatic Bootstrap.

    Set the Play mode type for the role you start

    Play Mode Type also restricts which roles you can start manually. Netcode.Connect fails when it's set to Server, and Netcode.Listen and Netcode.StartAsHost fail when it's Client. They log an error similar to the following, and return without connecting:

    Listen is not allowed if playmode is set to Client
    

    Leave Play Mode Type at Client & Server if your project chooses its role at runtime, which is what a connection menu does.

    Note

    When Multiplayer Content Selection is active, the active multiplayer role overrides Play Mode Type.

    Check the current role

    Query the role before you act on a connection, particularly in code that runs on both the client and the server:

    Property Meaning
    Netcode.IsClientRole This process has a client that's connecting or connected.
    Netcode.IsServerRole This process has a server that's listening.
    Netcode.IsHostRole This process has both a client role and a server role.
    Netcode.IsActive This process has online functionality running.

    IsClientRole and IsServerRole can both be true at once. These properties describe the current runtime state, so they change as a session starts and stops.

    Use Netcode.Listening() to check whether the server is currently listening for connections.

    A separate set of properties describes what the build supports, which doesn't change at runtime. Netcode.IsServerBuildOnly is true for a dedicated server build with client content stripped, Netcode.IsClientBuildOnly for a client build, and Netcode.IsClientServerBuild for a standalone build containing both. Use these to decide what a build does on startup, such as listening immediately in a dedicated server build.

    Respond to connection events

    Subscribe to Netcode.OnConnectionEvent to receive a callback when any connection changes state. The callback receives the Connection and a NetcodeConnectionEvent:

    public class ConnectionLogger : MonoBehaviour
    {
        void OnEnable()
        {
            Netcode.OnConnectionEvent += OnConnectionEvent;
        }
    
        void OnDisable()
        {
            Netcode.OnConnectionEvent -= OnConnectionEvent;
        }
    
        void OnConnectionEvent(Connection connection, NetcodeConnectionEvent evt)
        {
            if (evt.State == ConnectionState.State.Disconnected)
            {
                Debug.Log($"{connection.NetworkId.Value} left: {evt.DisconnectReason}");
                return;
            }
    
            Debug.Log($"{connection.NetworkId.Value} is now {evt.State}.");
        }
    }
    

    On a server, the callback fires for every client connection, not just your own. Compare against Netcode.LocalConnection when you only care about the local machine's connection.

    Control ghost replication

    Netcode enables ghost replication on a new connection as soon as it connects, on both the client and the server, so ghosts and inputs replicate right away.

    To pause replication, for example while a client loads a level, call Connection.EnableGhostReplication(false), and call Connection.EnableGhostReplication(true) to resume. While replication is paused, only RPCs flow.

    Important

    Both sides must do this: the client on its own connection, and the server on the connection representing that client. Enabling it on one side only is the most common reason snapshots don't arrive.

    To keep new connections limited to RPCs until your own code enables replication, disable Automatic State Replication on the NetcodeConfig asset.

    Ghost Prefab Loading Timeout on the NetcodeConfig asset controls what happens when a client doesn't have a ghost's prefab yet. Set the same value on the client and the server:

    • -1: the client tells the server which prefabs it has loaded, and the server only sends ghosts whose prefabs the client has. Clients can load prefabs in any order, for example with the scene that holds them.
    • A positive value: the same as -1, but the client logs an error and disconnects if a prefab is still missing after that many seconds.
    • 0: the client must load a ghost's prefab before the server sends that ghost. Otherwise, the client logs an error and disconnects.

    If no ghosts appear, check the connection state before you assume the connection failed. A connection that reports Connected but shows no ghosts has a replication problem, not a connection problem.

    Inspect a connection

    Member Returns
    NetworkId The connection's network ID, or NetworkId.Invalid if it doesn't have one yet.
    RTT The estimated round-trip time, or 0 if unavailable.
    World The NetcodeWorld the connection lives in. On a server this is the server world for every client connection.
    GetConnectionState() The current ConnectionState.State.
    IsValid() Whether this struct refers to a live connection.

    Get this machine's own connection from Netcode.LocalConnection. On a server or host, Netcode.AllConnections lists the connected clients.

    A Connection stops being valid after its connection closes. Fetch a connection when you need it rather than caching one across many frames, and call IsValid() before using one you have held onto.

    Handle the host's own connection

    On a host, the local client doesn't connect over the network. Netcode represents it with a connection that stands in for a real one, and it doesn't behave identically to a client that connects from outside:

    • Earlier availability: The host's connection is available as soon as the host starts listening, rather than after a handshake. Code that assumes a connection appears only in response to a connection event can encounter the host's connection before it expects any connection at all.
    • Constant connected state: GetConnectionState() returns Connected for the host's own connection whenever the server is listening, so it never passes through the intermediate states a remote client goes through.

    Disconnect and shut down

    Disconnects are asynchronous. None of these calls take effect until the next tick, so don't assume a connection is gone as soon as the call returns.

    // Disconnect one connection, from either side.
    connection.RequestDisconnect();
    
    // Client: leave the server.
    Netcode.RequestDisconnectFromServer();
    
    // Server: disconnect every client.
    Netcode.RequestDisconnectAllClients();
    

    Connection.RequestDisconnect takes an optional NetworkStreamDisconnectReason. The Disconnected event on the side that calls it reports this reason in DisconnectReason.

    To end a session entirely, call Netcode.Shutdown(), which shuts down and disposes every Netcode world, and destroys the ghosts in them. On a server, this raises a Disconnected event for each connection that's still open. Registered prefabs and Netcode.OnConnectionEvent callbacks are kept. To clear them too, pass reset: true. Pass false to keep the underlying worlds for reuse:

    Netcode.Shutdown(disposeWorld: false);
    

    After this call with world reuse, you can start only the same role again. For example, a client world can't start again as a host world. Call Netcode.Shutdown() without arguments before you switch roles.

    Additional resources

    • Get started with GhostObjects
    • Write prediction logic in a GhostBehaviour
    • Send events with RPCs and custom messages
    • Connecting server and clients
    • Client-hosted
    • Network topologies
    In This Article
    Back to top
    Copyright © 2026 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)