docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Replicate state over the network

    Author, replicate, and spawn a networked object using GameObjects and MonoBehaviours with GhostObjects.

    GhostObjects let you build server-authoritative multiplayer objects. You add a GhostObject component to a prefab, write your gameplay logic in a GhostBehaviour, and let Netcode replicate the object to connected clients. This page takes you through the key steps: creating a networked prefab, replicating state, and starting a session that spawns the object.

    For background on how GhostObjects work, refer to Introduction to GhostObjects.

    Create a networked prefab

    A networked object is a prefab with a GhostObject component on its root. The GhostObject component turns the GameObject into a ghost and holds the settings that control how Netcode replicates it.

    To create a networked prefab:

    1. Create a GameObject in your scene and add the components you need for your object, such as a mesh or collider.
    2. Drag the GameObject into your Project window to save it as a prefab.
    3. Open the prefab in prefab editing mode, or select the prefab asset in the Project window.
    4. In the Inspector window, select Add Component > Multiplayer > Ghost Object to add the GhostObject component to the prefab root.
    5. In the Inspector window, set the replication settings for the object on the GhostObject component. For more information about what these control, refer to GhostObject settings.

    The Inspector window only lets you change GhostObject settings on the prefab, not on its instances in a scene.

    You now have a prefab that Netcode can replicate. Netcode registers GhostObject prefabs automatically, so the server can spawn the prefab and clients can instantiate matching copies.

    GhostObject settings

    The tooltips describe each setting. For more information, refer to the following:

    • Importance and Max Send Rate
    • Snapshot History Size
    • Enable Prediction and Predict and Start as
    • Optimization Mode
    • Has Owner and Support Auto Command Target
    • Use Pre Serialization
    • Rollback Prediction > On Spawn
    • Rollback Prediction > On Structural Change
    • Full Tick Smoothing
    • Delayed Spawn
    • Parent Replication
    • Customize Serialization
    • Skip Automatic Prefab Registration

    Replicate state and add gameplay logic

    To add networked state and behavior to your object, create a MonoBehaviour that extends GhostBehaviour. Declare a GhostField for each value you want the server to replicate to clients, and override PredictionUpdate to run simulation logic inside the prediction loop. For more information about the prediction methods and APIs available to you, refer to Write prediction logic in a GhostBehaviour.

    If you already use the entity-based workflow, note that GhostField<T> in a GhostBehaviour is a different thing from the GhostFieldAttribute you apply to a component field. For more information, refer to Replicate and predict state.

    To replicate state and add gameplay logic:

    1. Create a script that extends GhostBehaviour and mark the class as partial. Netcode generates supporting code in the other half of the class, so you must declare the class partial.
    2. Declare a GhostField field for each value you want to replicate from the server to clients.
    3. Override PredictionUpdate to run any simulation logic you want predicted.
    4. If that logic reacts to player input, add a GhostInput<T> field and override PredictionGatherInput as well, so that prediction has the input it replays.
    5. Add the script to your networked prefab.

    The following example replicates a health value and reduces it once per tick:

    public partial class PlayerHealth : GhostBehaviour
    {
        // Replicated from the server to all clients.
        public GhostField<int> Health = new(100);
    
        public override void PredictionUpdate(PredictionUpdateContext context)
        {
            Health.Value -= 1;
        }
    }
    

    Netcode replicates each GhostField from the server to clients and rolls it back automatically during prediction. For more information about the prediction loop, refer to Prediction.

    GhostField<T> accepts numbers, bool, enums, Unity.Mathematics types such as float3, fixed-size strings such as FixedString64Bytes, NetworkTick, and unmanaged structs made of these types. It doesn't accept string, classes, arrays, or references to GameObjects or scripts.

    The GhostField constructor is optional, because GhostField is a value type that Netcode initializes automatically. The constructor can take an initial value and an optional FieldConfig. A GhostField that's public or has [SerializeField] shows in the Inspector window. Runtime edits are valid only on the authority.

    On a client, Awake already sees the replicated values it got from the server. On the server, Awake behaves as it does in an offline GameObject workflow: it sees the prefab values. Values you set after Instantiate aren't visible in the server's Awake, but they're visible in the client's Awake.

    For a complete example, refer to the GhostField sample in the Assets/GameObjectSample/0_Basics/1_GhostFields folder of the Netcode samples project. It replicates several value types, including a struct and a fixed-size string.

    Start a session and spawn the object

    To replicate objects, you need a running server or host and at least one connected client. Use the static Netcode class to start a session, then instantiate your prefab on the server. For more information, refer to Manage connections.

    To start a session and spawn the object:

    1. Start the networking role you need. Call Netcode.Listen on a dedicated server, Netcode.StartAsHost to have a client act as the server, or Netcode.Connect on a standalone client.
    2. On the server, instantiate the prefab to spawn the object.

    In the Unity Editor, Netcode can also start and connect automatically when you enter Play mode. For more information, refer to Connect automatically in the Editor.

    The following example starts a host and spawns an instance of a registered prefab:

    // Start a host: listen for clients and play as a local client at the same time.
    Netcode.StartAsHost(NetworkEndpoint.AnyIpv4.WithPort(7979));
    
    // On the server, instantiate the prefab. Netcode replicates it to clients automatically.
    var instance = Object.Instantiate(prefab);
    

    After you instantiate the prefab on the server, Netcode on each connected client spawns a matching copy and keeps its replicated state in sync. If a client doesn't receive the object, confirm that the prefab is registered and that the client is connected with ghost replication enabled. To test for a prefab loading problem, set Ghost Prefab Loading Timeout on the NetcodeConfig asset to 0. The client then logs an error and disconnects as soon as the server sends a ghost whose prefab the client hasn't loaded.

    For a complete example, refer to the spawn sample in the Assets/GameObjectSample/0_Basics/0_Spawn folder of the Netcode samples project. It spawns one object per connection on the server, sets its owner, and destroys it when the connection disconnects.

    Spawn an object from prediction

    You can instantiate a ghost prefab on the server, or on a client inside PredictionUpdate. On a client, this is a predicted spawn: the object appears right away, and the client keeps it when the server spawns the same prefab around the same tick, or removes it if the server never does. Run the same spawn logic on the server, and guard it so that replayed ticks don't spawn it again. Instantiating a ghost prefab on a client anywhere else logs an error and Netcode removes the object. On a host, instantiating inside PredictionUpdate is a normal server spawn, so test predicted spawns with a separate standalone client.

    Set up an object after you instantiate it

    Instantiate an object and set its values, as you would in a single-player project. Clients receive the object with the values you set.

    The following example spawns a player at a position with a starting health value and an owner. Assigning an owner requires Has Owner on the prefab:

    GameObject instance = Object.Instantiate(prefab, spawnPosition, Quaternion.identity);
    var playerHealth = instance.GetComponent<PlayerHealth>();
    playerHealth.Health.Value = 50;
    playerHealth.Ghost.OwnerNetworkId = owner.NetworkId;
    

    Control when an object spawns

    By default, Netcode sends a ghost to clients at the end of the frame in which you instantiate it. To decide yourself when Netcode sends it, use Delayed Spawn.

    To control when Netcode sends an object to clients:

    1. On the prefab, enable Delayed Spawn on the GhostObject component.
    2. Instantiate the prefab on the server. The server doesn't send the object yet.
    3. Call Spawn on the GhostObject component to start replicating the object to clients.
    4. To stop replicating the object, call Despawn. The object stays on the server, and you can call Spawn again later.

    When you call Spawn again after Despawn, the object gets a new ID and Netcode treats it as a new ghost. This differs from relevancy, which applies to specific connections and keeps the ghost's current ID.

    The following example keeps a pickup on the server and spawns or despawns it:

    static GhostObject pickup;
    
    static void CreatePickup()
    {
        pickup = Object.Instantiate(prefab).GetComponent<GhostObject>();
    }
    
    static void ShowPickup()
    {
        pickup.Spawn();
    }
    
    static void HidePickup()
    {
        pickup.Despawn();
    }
    

    Use IsSpawned to check whether the object is currently spawned. GhostField values you set before Spawn are sent when the object spawns, and they're kept across Despawn and Spawn.

    With Delayed Spawn enabled, you can only read or set OwnerNetworkId after Spawn. Before that, it logs a warning and reads as an invalid ID. Without Delayed Spawn, set the owner right after Instantiate, as shown in Set up an object after you instantiate it.

    For a complete example, refer to the delayed spawn sample in the Assets/GameObjectSample/1_Features/1_DelayedSpawn folder of the Netcode samples project. It instantiates objects on the server and spawns, despawns, or destroys each one from a menu.

    Register a prefab yourself

    Netcode registers a GhostObject prefab automatically when the prefab asset loads. Once a prefab is registered, you can't change its GhostObject settings. To change them from code first, enable Skip Automatic Prefab Registration on the GhostObject component and register the prefab yourself.

    To register a prefab yourself:

    1. On the prefab, enable Skip Automatic Prefab Registration on the GhostObject component.
    2. In your code, change the GhostObject settings you need.
    3. Call Netcode.RegisterPrefab with the prefab.

    The following example enables Has Owner on a prefab, then registers it:

    // The prefab has Skip Automatic Prefab Registration enabled, so its settings can still change.
    prefab.GetComponent<GhostObject>().HasOwner = true;
    Netcode.RegisterPrefab(prefab);
    

    For a complete example, refer to the register prefabs sample in the Assets/GameObjectSample/0_Basics/6_RegisterPrefabs folder of the Netcode samples project. It registers prefabs when their scenes load, with both automatic and manual registration.

    Additional resources

    • Introduction to GhostObjects
    • Synchronization with ghosts
    • Prediction
    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)