docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Get started with GhostObjects

    Build a multiplayer scene from an empty project, where every connected player controls a server-authoritative, client-predicted GameObject.

    This page takes an empty Unity project to a running multiplayer scene. Each connected player owns a cube that they can move, rotate, scale, and make jump. The server simulates every cube authoritatively and the owning client predicts its own cube locally, so input feels immediate while the server keeps control of the outcome. All the scripts you need are on this page, so you don't need a sample or an existing project setup to follow it.

    Use this page if you're new to GhostObjects and want a complete, working project to build on. It covers how to run the project as a host with a second player in Multiplayer Play Mode. It also covers how to spawn a networked object that only its owner can control, how to replicate state, and how to predict movement on the owning client.

    For background on how GhostObjects work, refer to Introduction to GhostObjects. To replicate state in a project that's already set up, refer to Replicate state over the network. To use GhostObjects alongside entity-based ghosts, refer to Hybrid GhostObjects and entities in the same project.

    Prerequisites

    Before you start, complete the following:

    1. Install Unity 6000.7 or later.
    2. Create a project with the Universal 3D template.
    3. Install the Input System package (com.unity.inputsystem). When Unity prompts you to change the active input handling, accept the change and let the Unity Editor restart.

    Accepting the change sets Active Input Handling in your player settings to Input System Package (New), which the PlayerController script later in this page depends on.

    Configure the player settings

    Netcode requires the application to keep simulating when its window loses focus, which happens constantly when you test with several instances on one device.

    To configure the player settings:

    1. Go to Edit > Project Settings > Player. In the Resolution and Presentation section, enable Run In Background.
    2. In the Other Settings section, confirm that Active Input Handling is Input System Package (New) or Both.

    With Run In Background enabled, a window that loses focus keeps simulating instead of stalling. If you leave it disabled, Netcode logs an error during play and the connection times out.

    Add the scripts

    This project uses three files: an assembly definition and two scripts. The assembly definition references the packages the scripts need.

    Create a folder named Assets/Scripts and add each of the following files to it.

    Define the assembly

    To create the assembly definition:

    1. In the Project window, create an assembly definition asset in Assets/Scripts and name it GhostObjectsSample.
    2. Open Assets/Scripts/GhostObjectsSample.asmdef in a text editor and replace its contents with the following:
    {
        "name": "GhostObjectsSample",
        "rootNamespace": "GhostObjectsSample",
        "references": [
            "Unity.NetCode",
            "Unity.Entities",
            "Unity.Collections",
            "Unity.Burst",
            "Unity.Mathematics",
            "Unity.Networking.Transport",
            "Unity.InputSystem"
        ],
        "includePlatforms": [],
        "excludePlatforms": [],
        "allowUnsafeCode": false,
        "overrideReferences": false,
        "precompiledReferences": [],
        "autoReferenced": true,
        "defineConstraints": [],
        "versionDefines": [],
        "noEngineReferences": false
    }
    

    The scripts in the following sections compile into this assembly.

    Spawn one player per connection

    When you enter Play mode, Netcode starts a session automatically with the role set in Play Mode Type, as described in Connect automatically in the Editor. This script only has to react to connections.

    Outside of predicted spawns, only the server instantiates ghosts, and clients receive matching copies over the network. The following script instantiates one cube per connection, assigns ownership of that cube to the connection, and destroys the cube when its owner disconnects.

    To create the spawner:

    1. In Assets/Scripts, create a C# script named PlayerSpawner.cs.
    2. Replace the contents of the script with the following code:
    public class PlayerSpawner : MonoBehaviour
    {
        [SerializeField] GameObject m_PlayerPrefab;
    
        // One player per connected client, keyed by network ID.
        readonly Dictionary<int, GameObject> m_Players = new Dictionary<int, GameObject>();
    
        void Awake()
        {
            Netcode.OnConnectionEvent += OnConnectionEvent;
    
            // The host's own connection doesn't raise a connection event after Awake, so spawn its player here.
            if (Netcode.IsHostRole)
            {
                SpawnPlayer(Netcode.LocalConnection);
            }
        }
    
        void OnDestroy()
        {
            Netcode.OnConnectionEvent -= OnConnectionEvent;
        }
    
        void OnConnectionEvent(Connection connection, NetcodeConnectionEvent evt)
        {
            if (evt.State == ConnectionState.State.Disconnected)
            {
                // Read the network ID from the event, because the connection is
                // already gone when a disconnect arrives.
                DespawnPlayer(evt.Id.Value);
                return;
            }
    
            if (evt.State != ConnectionState.State.Connected)
            {
                return;
            }
    
            // Only the server instantiates ghosts outside of prediction.
            if (!connection.World.IsServer())
            {
                return;
            }
    
            SpawnPlayer(connection);
        }
    
        void SpawnPlayer(Connection connection)
        {
            GameObject playerInstance = Object.Instantiate(
                m_PlayerPrefab,
                transform.position,
                transform.rotation);
    
            // Assign ownership so that only this connection can drive the cube.
            GhostObject ghost = playerInstance.GetComponent<GhostObject>();
            if (ghost.HasOwner)
            {
                ghost.OwnerNetworkId = connection.NetworkId;
            }
    
            m_Players[connection.NetworkId.Value] = playerInstance;
        }
    
        void DespawnPlayer(int networkId)
        {
            if (m_Players.TryGetValue(networkId, out GameObject playerInstance))
            {
                m_Players.Remove(networkId);
                Object.Destroy(playerInstance);
            }
        }
    }
    

    Netcode enables ghost replication for each connection automatically, so a client receives the ghosts as soon as it connects.

    Move, rotate, and scale the player

    The behavior on the cube is a GhostBehaviour. PredictionGatherInput runs on the owning client and captures a PlayerInput. Netcode sends that input to the server automatically, because the prefab has an owner. PredictionUpdate runs inside the prediction loop, on the server and on the owning client, and applies movement, rotation, and scale to the transform, which Netcode replicates and rolls back for you.

    The controller also keeps the vertical speed of its jump in a GhostField<float>, to show how to replicate state that isn't part of the transform. Prediction rolls the value back and replays it with the transform, and every client receives it.

    To create the player controller:

    1. In Assets/Scripts, create a C# script named PlayerController.cs.

    2. Replace the contents of the script with the following code:

      public struct PlayerInput : IInputComponentData
      {
          // Strafe on x, and move forward or back on y.
          public Vector2 Move;
      
          public float Yaw;
          public float Scale;
      
          // A key press lasts one frame. InputEvent makes sure the tick sees it.
          public InputEvent Jump;
      }
      
      public partial class PlayerController : GhostBehaviour
      {
          [SerializeField] float m_MoveSpeed = 5f;
          [SerializeField] float m_YawSpeed = 120f;
          [SerializeField] float m_ScaleSpeed = 1.5f;
          [SerializeField] float m_MinScale = 0.3f;
          [SerializeField] float m_MaxScale = 3f;
          [SerializeField] float m_JumpSpeed = 6f;
          [SerializeField] float m_Gravity = 20f;
      
          // Input for this ghost, captured by PredictionGatherInput on the owning client.
          GhostInput<PlayerInput> m_Input;
      
          // Replicated so that prediction rolls it back with the transform.
          GhostField<float> m_VerticalSpeed;
      
          // Runs on the owning client only, before the prediction loop.
          public override void PredictionGatherInput(PredictionGatherInputContext context)
          {
              PlayerInput input = m_Input.PrepareToCapture();
              Keyboard keyboard = Keyboard.current;
      
              if (keyboard != null)
              {
                  if (keyboard.aKey.isPressed || keyboard.leftArrowKey.isPressed)
                  {
                      input.Move.x -= 1f;
                  }
                  if (keyboard.dKey.isPressed || keyboard.rightArrowKey.isPressed)
                  {
                      input.Move.x += 1f;
                  }
                  if (keyboard.sKey.isPressed || keyboard.downArrowKey.isPressed)
                  {
                      input.Move.y -= 1f;
                  }
                  if (keyboard.wKey.isPressed || keyboard.upArrowKey.isPressed)
                  {
                      input.Move.y += 1f;
                  }
      
                  if (keyboard.qKey.isPressed)
                  {
                      input.Yaw -= 1f;
                  }
                  if (keyboard.eKey.isPressed)
                  {
                      input.Yaw += 1f;
                  }
      
                  if (keyboard.rKey.isPressed)
                  {
                      input.Scale += 1f;
                  }
                  if (keyboard.fKey.isPressed)
                  {
                      input.Scale -= 1f;
                  }
      
                  if (keyboard.spaceKey.wasPressedThisFrame)
                  {
                      input.Jump.Set();
                  }
              }
      
              m_Input.Capture(input);
          }
      
          // Runs once per tick on the server, and once or more per frame on the
          // predicting client. Replicated state and the transform are rolled back
          // and resimulated.
          public override void PredictionUpdate(PredictionUpdateContext context)
          {
              PlayerInput input = m_Input.GetForCurrentTick();
      
              // Jump, then fall back to the ground at y = 0.
              if (input.Jump.IsSet)
              {
                  m_VerticalSpeed.Value = m_JumpSpeed;
              }
              m_VerticalSpeed.Value -= m_Gravity * context.TickedDeltaTime;
      
              Vector3 move = new Vector3(input.Move.x, 0f, input.Move.y).normalized * m_MoveSpeed;
              move.y = m_VerticalSpeed.Value;
              transform.position += move * context.TickedDeltaTime;
              if (transform.position.y < 0f)
              {
                  transform.position = new Vector3(transform.position.x, 0f, transform.position.z);
                  m_VerticalSpeed.Value = 0f;
              }
      
              // Rotate around the world Y axis.
              transform.Rotate(
                  Vector3.up,
                  input.Yaw * m_YawSpeed * context.TickedDeltaTime,
                  Space.World);
      
              // Scale uniformly. Netcode replicates the GameObject's scale, so read the
              // current scale from the transform.
              float scale = Mathf.Clamp(
                  transform.localScale.x + input.Scale * (m_ScaleSpeed * context.TickedDeltaTime),
                  m_MinScale,
                  m_MaxScale);
              transform.localScale = new Vector3(scale, scale, scale);
          }
      }
      
    3. Save the scripts and wait for the Editor to recompile.

    PlayerController reads input through Keyboard.current, which comes from the Input System package.

    PlayerController holds its input in a GhostInput<PlayerInput>. The input type must be a struct that implements IInputComponentData. PredictionGatherInput starts from the empty input that the optional PrepareToCapture returns, fills it with the keys held this frame, and hands it over with Capture. Netcode doesn't reset the input between frames, so capture from a fresh input, either PrepareToCapture() or new PlayerInput(). Capturing from GetForCurrentTick() or a stored input counts InputEvent presses twice. PredictionUpdate reads the input for the tick it simulates with GetForCurrentTick.

    The jump is an InputEvent rather than a bool, because a key press lasts a single frame. PredictionGatherInput runs every frame, but a tick doesn't, so a bool set on one frame can be replaced by the next frame's capture before a tick reads it, or be lost on its way to the server. InputEvent counts presses, so each press reaches exactly one tick on the server. Use InputEvent for any one-off action, such as jumping or firing, and check it with IsSet.

    Create the player prefab

    To create the player prefab:

    1. In the main menu, go to GameObject > 3D Object > Cube, and rename the cube Player.
    2. In the Inspector window, select Add Component and add the Player Controller component.
    3. Drag Player from the Hierarchy window into Assets/Prefabs in the Project window, and then delete the instance from the scene.
    4. In the Project window, select the Player prefab. Select the prefab asset, not the cube in the scene.
    5. In the Inspector window, select Add Component > Multiplayer > Ghost Object to add the GhostObject component to the prefab.
    6. In the GhostObject component, enable Has Owner.
    7. In the Prediction and Interpolation section, enable Enable Prediction, and then set Predict to Only on Owner.
    8. In the Player Controller component, adjust the movement, rotation, scale, and jump values if you want to.

    You now have a prefab that Netcode can replicate, and that only its owner can drive. Only on Owner means the owning client predicts the cube while every other client interpolates it. If a cube doesn't respond to input later, or the wrong cube moves, check these two settings first. For more information about ghost modes, refer to Synchronization with ghosts.

    Set up the scene

    The scene needs the spawner, and the spawner needs a reference to the player prefab.

    To set up the scene:

    1. Open or create a scene, for example Assets/Scenes/Main.unity, and keep its default camera and directional light.
    2. Create an empty GameObject at the world origin and rename it PlayerSpawner.
    3. Add the Player Spawner script as a component to PlayerSpawner.
    4. In the Inspector window, set Player Prefab on the Player Spawner component to the Player prefab.
    5. Save the scene, and then add it as the first scene in your build profile.

    Keep the spawner and its prefab reference in this scene, so that the player prefab loads with the scene. If the host's own cube doesn't appear when you test the project, confirm that you assigned Player Prefab.

    Test the project in Multiplayer Play Mode

    If you enter Play mode now, a host starts, which is similar to a single-player game. To test a connection, run the host and each client in separate instances. Multiplayer Play Mode creates that second instance as a virtual player Editor.

    To test the project:

    1. Install the Multiplayer Play Mode package.
    2. Go to Window > Multiplayer > Multiplayer Play Mode, and activate Player 2.
    3. Enter Play mode. The host listens on port 7979, and Player 2 connects to it automatically.
    4. Press W, A, S, and D, or the arrow keys, to move a cube.
    5. Press Q and E to rotate the cube.
    6. Press R and F to scale the cube.
    7. Press Space to jump.

    Each instance spawns its own cube. The owning client predicts your input locally and the host applies it authoritatively. The other instance sees your cube move, rotate, and scale through replication, and you can't drive a cube you don't own. If nothing connects, confirm that a second instance is running, because a single Editor instance can't complete a connection to a host.

    To connect from a build or another device, add a connection menu, as described in Manage connections and shown in the connection sample in the Assets/GameObjectSample/0_Basics/4_Connection folder of the Netcode samples project.

    Additional resources

    • Introduction to GhostObjects
    • Replicate state over the network
    • Client-hosted
    • 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)