Build a session with Netcode for GameObjects

Build a multiplayer game with sessions using Netcode for GameObjects for projects with GameObject and MonoBehaviour workflows.

Note: The Multiplayer Services SDK uses sessions to manage groups of players. Sessions relies internally on different combinations of Unity Gaming Services such as Relay, Distributed Authority, Lobby, Matchmaker and Multiplay Hosting, and thus contributes to the billing of those services.

To start a multiplayer game, the host must create a session that other players join to participate in the game. A session represents a group of players that are connected together for a set period of time during a multiplayer game.

To learn the principles of Multiplayer Services sessions, explore a simple multiplayer game of moving capsules. In this tutorial, you create one capsule controlled by the session's host and another capsule controlled by a joining player, as well as the necessary game objects and code to add session management to your game.

Prerequisites

In addition to the Multiplayer Services package, ensure that you install the following packages through the Unity Registry in the Editor's Package Manager:

  • Widgets (or com.unity.multiplayer.widgets): Enables you to test multiplayer services without having to write code.
  • Multiplayer Play Mode (or com.unity.multiplayer.playmode): Enables you to test multiplayer functionality without leaving the Unity Editor.
  • Netcode for GameObjects (or com.unity.netcode.gameobjects): Provides networking capabilities to GameObject and MonoBehaviour workflows.

Configure Multiplayer Play Mode

To configure Play Mode for your project to test multiple players:

  1. In the Unity Editor, go to Window > Multiplayer > Multiplayer Play Mode.
  2. In the Multiplayer Play Mode window, enable Player 2.

After adding Player 2, you can test the project with a second window.

Set up Netcode for GameObjects

Note: If you are using Netcode for Entities, refer to its instructions instead.

To set up Netcode for GameObjects, attach a Network Manager component to a GameObject:

  1. In the Unity Editor, select GameObject > Create Empty to create a new GameObject in your scene.
  2. Rename it NetworkManager.
  3. Select this NetworkManager you just created.
  4. Select Component > Netcode > Network Manager to attach a Network Manager component.
  5. In the Inspector window, go to Network Transport and select UnityTransport.

Netcode for GameObjects is now set up in your project.

Create client network transform

Netcode for Game Objects assigns authority of every networked object to the server (or host) by default. The following script overrides this behavior for player prefabs and gives authority to the owning client, greatly improving the reactiveness of player movement, especially in poorer network conditions.

To override server-assigned object authority:

  1. In the Project tab, right-click the Assets folder, then Create > Folder.
  2. Name the new folder Scripts.
  3. Right-click the new Scripts folder, then Create > Scripting > Empty C# Script.
  4. Rename this script ClientNetworkTransform.cs
  5. Replace the contents of this script with the following code:
    using UnityEngine;
    using Unity.Netcode.Components;
    
    [DisallowMultipleComponent] // Prevents you from adding the ClientNetworkTransform to the object more than once.
    public class ClientNetworkTransform : NetworkTransform
    {
        /// <summary>
        /// Used to determine who can write to this transform. Owner client only.
        /// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
        /// </summary>
        protected override bool OnIsServerAuthoritative()
        {
            return false;
        }
    }

Clients now have authority over their networked objects, which provides improved performance.

Create the player Prefab

To create a Prefab from a network-enabled capsule:

  1. In the Unity Editor, go to Edit > Project Settings > Player > Other Settings > Configuration > Active Input Handling, then select Both. Changing the input handling might trigger a restart of your Unity Editor.
  2. Close Project Settings.
  3. Right-click within the Hierarchy window, then select 3D Object > Capsule.
  4. Rename the capsule to Player Prefab.
  5. With this capsule selected, in the Inspector window, select Add Component > Netcode > Network Object.
  6. In the Project tab, right-click the Scripts folder, then Create > Scripting > Empty C# Script.
  7. Rename this script PlayerController.cs.
  8. Replace the contents of this script with the following code:
    using UnityEngine;
    using Unity.Netcode;
    
    public class PlayerController : NetworkBehaviour
    {
        public float speed = 20;
    
        private ClientNetworkTransform _transform;
    
        private void Start()
        {
            _transform = GetComponent<ClientNetworkTransform>();
        }
        private void Update()
        {
            if (!IsOwner) return;
            var movement = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
            _transform.transform.position += movement * speed * Time.deltaTime;
        }
    
    }
  9. With the capsule player selected in the Hierarchy window, attach the PlayerController script to its Inspector window. If you receive a prompt that Network Behaviors require a NetworkObject, select Yes to add one.
  10. Still in the Inspector window, select Add Component.
  11. Search for Client Network Transform, then add it.
  12. In the Project window, right-click Assets, then Create > Folder.
  13. Rename this folder Prefabs. Refer to Prefabs.
  14. Make the Player Prefab object you created earlier into a Prefab by dragging it from the Hierarchy window into the Prefabs folder.
  15. Delete the player from the scene by right-clicking the capsule within the Scene window, then Delete.

    Tip: You can remove the player GameObject from the scene because you assigned this network Prefab to the player Prefab property in the NetworkManager component. The library doesn't support defining a player object as an in-scene placed NetworkObject.

  16. In the Hierarchy window, select NetworkManager.
  17. In its Inspector window, locate the Default Player Prefab field.
  18. Drag the capsule player from the Project window into the Default Player Prefab field you located.
  19. In the Unity Editor, select File > Save.

At this point, a network-enabled capsule is the default player prefab for the GameObject called NetworkManager.

Add your scene to the build

In Inspector window for NetworkManager, locate the Enable Scene Management setting (enabled by default). When you enable it, the server can control which scenes load for the clients. However, you must add the current scene to the build to enter Play Mode.

To add the current scene to the build:

  1. In the Unity Editor, select File > Build Profiles.
  2. Select Open Scene List.
  3. Select Add Open Scenes.
  4. Close Build Profiles.

The current scene is now included in the build.

Create and join your first session with Widgets and Multiplayer Services

The following steps outline how to create and join your first session with Widgets and Multiplayer Services in the Unity Editor.

Make sure Multiplayer Play Mode is enabled.

  1. Right-click in the Hierarchy window, then select Multiplayer Widgets > Create > Create Session.

    Note: If you receive a TMP Importer prompt, select Import TMP Essentials.

  2. In the Hierarchy window, select Canvas > Create Session.
  3. In its Inspector window, set Rect Transform > Pos Y to 50.
  4. Right-click in the Hierarchy window, then select Multiplayer Widgets > Info > Show Session Code.
  5. Right-click in the Hierarchy window, then select Multiplayer Widgets > Join and Leave > Join Session By Code.
  6. In the Hierarchy window, select Canvas > Join Session By Code.
  7. In its Inspector window, set Rect Transform > Pos Y to -100.
  8. In the Unity Editor, select File > Save to refresh the scene for Player 2.
  9. In the Toolbar, select Play to enter Play Mode.
  10. In the Game window's Session Name field, enter a name, then select Create.
  11. Copy the session join code.
  12. In the Player 2 window's Session Code field, enter the code and then select Join.

After Player 2 joins the session, two superimposed capsules appear in the scene.

Move the capsules

To move the capsules in your multiplayer session:

  1. Click within the Game window of the Editor.
  2. Use the arrow keys on your keyboard to move the capsule around the scene. It moves in real time in both the Game window and the Player 2 window.
  3. Click within the Player 2 window.
  4. Use the arrow keys on your keyboard to move the capsule around the scene. Notice that the other capsule (Player 2's capsule) moves this time.

When you enter Play Mode and join the session, you now have a scene of two capsules that can be controlled only by the owning player.

Additional resources