Getting started with Unity Multiplayer Networking — Part 2

Thomas Steffen
2 min readSep 12, 2023

--

In my last article, I wrote out how to set up the initial phase of connecting a host and client. Now I’m going to explain how to get each player moving separately.

We can begin our player script by utilizing the Unity.Netcode library. We will also replace Monobehaviour with NetworkBehaviour:

using Unity.Netcode;
using UnityEngine;

public class Player : NetworkBehaviour
{
}

After writing some simple movement code, add this to your Update() function:

    private void Update()
{
if (!IsOwner) return;

PlayerMovement();
}

You could write a more advanced movement system or for testing purposes, just use a simple movement method such as:

private void Update()
{
if (Input.GetKey(KeyCode.W)) moveDir.z = +1f;
if (Input.GetKey(KeyCode.S)) moveDir.z = -1f;

float moveSpeed = 3f;
transform.position += moveDir * moveSpeed * Time.deltaTime;
}

This will move your character forward and back with the “W” and “S” keys.

After building again and running in Unity, you will notice we now move individually! However, our movement is not synced up with each other. So let’s add a component to our Player called NetworkTransform.

We can choose what information is transferred across the network. If our scale will never change, we should uncheck those marks, as we do not want to be consistently sending unnecessary information. Same thing, if your character doesn’t rotate or if they never jump/move on the y axis. Make sure you are minimizing the amount of data being transferred.

As of now, only the Host can move, but it is synced. The Client cannot move because it does not have the server authority to move. Depending on your type of game, you can structure your code and authorization differently.

One option is to use the ClientNetworkTransform. Netcode for GameObjects comes with a sample containing a ClientNetworkTransform. This transform synchronizes the position of the owner client to the server and all other client allowing for client authoritative gameplay. You will need the Git link:

You can paste the GIT URL directly into Unity’s package manager to download.

In a later article, I will cover the RPC method. But for now, I removed the NetworkTransform component from our player and added the component ClientNetworkTransform. This has the same parameters as the Network Transform we had before. If you open the script, you will see that the only difference is that it changes the server authority.

After creating another build, you should notice that your characters are now synced up when moving on Host and Client!

--

--

Thomas Steffen
Thomas Steffen

Written by Thomas Steffen

I am Virtual Reality Developer, UI Systems, and general programmer with a passion for Unity software development.

No responses yet