How to Create a Simple Multiplayer Game in Unity – a Beginner’s Guide

Share

In this article, I will show you how to add Mirror to your Unity project, and create a simple multiplayer game. You can also download the project files from GitHub. Mirror is a networking library, which allows you to easily create multiplayer games in Unity. It is free, open-source, and it is actually a fork of UNET, Unity’s own deprecated networking API.

The Game

Each player receives a “sphere”, and can move on a table. Other players can see it, and the spheres can hit each other. The goal of the game is to push other spheres down from the table.

Setting up The Scene

Add a “Cube” to your scene and increase its size to make a table. Also add a “Sphere” 3D game object. You can change the Material in the Mesh Renderer component for both the sphere and the table (I set them to “Dirt” and “PlayArea”).

Then add a Rigidbody component to the Sphere. Create a Prefab folder under your assets and drag-and-drop the sphere it into it. We will need the sphere as a prefab for the next steps.

You can now remove the sphere from the scene, it will just confuse Mirror.

Moving the Sphere

We want to move our sphere by arrows in all directions until it falls from the table. Create a folder “Scripts” and a C# script “SphereController.cs”.

using UnityEngine;

public class SphereController : MonoBehaviour {
    
    private float speed = 0.05f;

    void Update()
    {
           Vector3 movement = new Vector3(Input.GetAxis("Horizontal") * speed, 0, Input.GetAxis("Vertical") * speed);
           transform.position = transform.position + movement;  
    }
}

Unity calls the Update method with every frame, so we repeatedly check the input, if the player clicked on any arrow buttons on the keyboard. We change the position of the sphere according to the respective button and the pre-defined speed.

Finally, add the SphereController component to your Sphere prefab. Now, we are ready with our single-player game. Let’s turn this into a multiplayer game!

Import Mirror Networking to Your Project

Go to Window > Asset Store, and search for Mirror. Click on Download, and if you have downloaded, click on Import. This will add all the Mirror libraries to your assets.

Configure Mirror Networking

Create a new Game Object called “NetworkManager” into your scene. We will add the Mirror components to this object.

At first, let’s add the “NetworkManager” component. This will automatically add the “Kcp Transport” component by default. With earlier Mirror versions they added the Telepathy Transport, now Mirror recommends KCP, because it performs better than the TCP transport.

Drag and drop your “Sphere” from the Prefab folder into the NetworkManager component, Player Object > Player Prefab. Mirror will spawn (create) an instance of this game object for each client.

We also want to add a component called “NetworkManagerHUD”, which is a simple UI with buttons and an edit field for hosting a game or joining to any machine with the defined IP address. Definitely nothing for productive use, but it helps to start quickly.

Now go to our “Sphere” prefab, and add the “NetworkIdentity” component to it. Mirror will only consider objects with a network identity, so this is crucial.

Because we want to move our sphere, add also the “NetworkTransform” component to it. This synchronizes all the Transform parameters (position, rotation, scale) over the network which is exactly what we need for our game.

SyncToy for Multiplayer Development

We want to test our game from the perspective of multiple players. You can just build multiple instances of your game and start it, but it is more convenient to have two Unity Editors running with your project representing the two players.

So first, you need a copy of your project. Second, you need a tool that keeps the second project in sync with the original one. There are multiple tools to support this, I’d suggest SyncToy, which is from Microsoft and completely free.

When you start it, you need to “Create a New Folder Pair”, set your project folder to the “Left Folder”, and create a new empty folder for your project clone. Then set the “Echo” so that SyncToy copies any changes from the original project to the cloned project. Be aware that this will only happen if you click explicitly on “Run”, and SyncToy will only “echo” the changes, so if you change the cloned project, the original project will not take over the changes.

Also Unity may block some files from cloning and you get errors when syncing in the SyncToy. Then just exclude those files and folders (Change options… > Select subfolder), because you don’t need to clone everything from your project folder.

Finalize Your Code

Now that all the configuration is ready, let’s make some changes to the code, so it works in multiplayer mode. First, using the Mirror namespace, let’s inherit our SphereController class from NetworkBehaviour instead of MonoBehaviour. In this way you can also apply the networking features of Mirror, but you also keep all capabilities of MonoBehaviour (NetworkBehaviour is actually a child of MonoBehaviour).

After multiple players join the game, Mirror will spawn new players (spheres) on the scene. The SphereController will run on all of them, so we need to decide which sphere belongs to the actual controlling player. The “isLocalPlayer” value helps in this. If we would NOT put the isLocalPlayer condition in the code, then when the player clicks on arrows, not just the own spheres would move, but all of them. You can try it out!

using UnityEngine;
using Mirror;

public class SphereController : NetworkBehaviour {
   
    private float speed = 0.05f;

    void Update()
    {
        if (isLocalPlayer) {
           Vector3 movement = new Vector3(Input.GetAxis("Horizontal") * speed, 0, Input.GetAxis("Vertical") * speed);
           transform.position = transform.position + movement;
        }
        
    }
}

By default, the server has authority over all objects. Let’s set the “Client Authority” on the NetworkTransform component… and our first multiplayer game is ready.

If you start both of your game instances (the original and the clone) in your separate Unity Editors, you will see a panel with buttons and an editable field in the upper left corner. This is the “NetworkManagerHUD” component. Start a Host, which is a server, but it also starts a client. If you are on the same machine, start a Client on the other Unity Editor with “localhost”. You can also experiment to build an instance and start it on another machine. Then you need to set the IP of the host machine instead of localhost. Have fun!

This simple example shows all the basic configuration for a multiplayer game using Mirror Networking. There is a lot of potential to improve it. The goal was here to show the basic elements of Mirror and show how you can use them in Unity.


Share

Leave a Comment

Your email address will not be published.

Scroll to Top