Using Unity for Multiplayer Networking

Raka Mahesa

July 05th, 2016

Multiplayer is hard. And online multiplayer is really, really hard. Fortunately, starting with version 5.1, Unity has a brand new multiplayer networking solution that was built right into the game engine. So how does it work? How can you use it? Let's find out.

Unity's multiplayer solution consisted of multiple parts. The first one is a high-level API that allows developers to easily sync GameObjects over a network. The next part is a low-level API that provides a secure way to communicate between clients. And the last one is a service that provides various multiplayer utilities such as matchmaking, lobby joining, and relay server.

We'll focus solely on the on the high-level API this time, since that's the one that provides the quickest way to have a multiplayer game up and running. Okay, let's dive right in and test out it out ourselves!

Note: The following project is done in Unity 5.3.

We’ll start by creating a new project with an empty new scene. After that's done, we're going to need an object with a NetworkManager component in that scene, so let's create an empty GameObject and add the NetworkManager script to it. Since this component will be central to the whole networking system, we'll need to take a closer look at it.

 

The most important field on this component is the "Player Prefab" field. When the game is connected to a multiplayer session, NetworkManager will automatically spawn a player object on each connected client. The spawned object will be based on the prefab that was assigned to that field, so our next step will be to create a prefab that will represent the player in the game.

In my project, I chose to use a simple cube as the prefab, but feel free to use whatever object you want to be the prefab. You can also use an empty GameObject as the prefab if the game doesn't have a controllable character, like if it's an RTS or a card game. Next, we need to add a NetworkIdentity component to the prefab and make sure the "Local Player Authority" field is checked. That component will indicate that it's an object that will be shared over the network, and that particular field indicates that the object is connected to a player instead of just a neutral game entity like a monster or an NPC. The last step is to assign the prefab to the Player Prefab field, and you're done.

By default, the NetworkManager will spawn the player object at coordinate (0, 0, 0). But we want the game to have different spawning positions for each player, so we need to define new spawn points for the players. To do that, select the object with the NetworkManager component and add a new script with the following content:

void Start() {
	//Create spawning positions
	GameObject player1 = new GameObject("Player 1 position");
	GameObject player2 = new GameObject("Player 2 position");
	player2.transform.localRotation = Quaternion.Euler(0, 180, 0);
	player1.transform.localPosition = new Vector3(0, 0.5f, -7f);
	player2.transform.localPosition = new Vector3(0, 0.5f, 7f);

	//Register positions
	NetworkManager.singleton.playerSpawnMethod = PlayerSpawnMethod.RoundRobin;
	NetworkManager.singleton.startPositions.Add(player1.transform);
	NetworkManager.singleton.startPositions.Add(player2.transform);
}

All right, it is time to check whether the game can connect with other players. To test the multiplayer feature quickly, you can simply have two instances of the game running together, one as the host and the other as a client. So first call the function NetworkManager.singleton.StartHost() right after you define the new spawn positions and build the project to a standalone executable (File > Build and Run). Next, you're going to need a client, so replace that function you just added with NetworkManager.singleton.StartClient() to connect as a client.

Now run the stand-alone application first and then simply play the game from the Unity editor. If all went well, you should have two player objects on the game. Congratulations, you just made a working multiplayer game!

With the multiplayer feature working, let's add player movement to the game. To do this, we're going to need two more things to add to the player prefab. The first one is a component called NetworkTransform. This component will allow the object's position, rotation, and scale to be automatically synced over the network.

The other thing we need to add to the prefab is a new script that will read player's input and move the object. Unlike your regular script, however, this new script will have to derive from the NetworkBehavior class instead of MonoBehavior. By inheriting from NetworkBehavior, the script will have access to additional functionalities that were specifically made to handle various networking situations. Then, to make the object move around, simply add the following lines to the Update() method:

//If local player
if (isLocalPlayer) {
	//Check rotation input
	float angle = 0;
	if (Input.GetKey(KeyCode.A)) angle -= 90f;
	if (Input.GetKey(KeyCode.D)) angle += 90f;

	//Rotate
	float finalAngle = transform.localRotation.eulerAngles.y + angle * Time.deltaTime;
	transform.localRotation = Quaternion.Euler(0, finalAngle, 0);

	//Check movement input
	Vector3 movement = Vector3.zero;
	if (Input.GetKey(KeyCode.W)) movement += transform.forward * 4;
	if (Input.GetKey(KeyCode.S)) movement -= transform.forward * 4;

	//Move
	transform.localPosition += movement * Time.deltaTime;
}

You may notice that the code above has a reference to the IsLocal variable, which is one of those additional functionalities I talked about before. That check was needed because in multiplayer Unity projects, the code will run on all the connected clients instead of just in your game. So, if you don't check whether it's a player-controlled object or not, your input will move all the player objects instead of just your own.

And that's it! Try running another multiplayer session like I wrote earlier and you'll be able to move the objects separately on each client. We’ve really only touched the basics of Unity’s multiplayer feature here, but I hope that's enough for you to understand how multiplayer works in Unity. Check out this comprehensive tutorial if you're interested in developing a more advanced multiplayer game. Good luck!

About the author

Raka Mahesa is a game developer at Chocoarts (http://chocoarts.com/) who is interested in digital technology in general. Outside of work hours, he likes to work on his own projects, with Corridoom VR (https://play.google.com/store/apps/details?id=com.rakamahesa.corridoom) being his latest released game. Raka also regularly tweets as @legacy99 at https://twitter.com/legacy99.