How To Create An Online Multiplayer Game With Unity

Published on:
/ month
placeholder text

The gaming industry has changed beyond recognition over the last couple of decades. Besides new storylines, ultra-realistic graphics and dynamics, and immersive gameplay, gamers expect every game these days to have a multiplayer option. In fact, most gamers today prefer multiplayer games to regular single player games. This is especially true of console gamers. 

Maybe you are an obsessive gamer and have decided to try your hand in game design and development. You may even plan on starting your own game development company. While the bar has been set pretty high, it is also immeasurably easier to create games, thanks to the tools you have at your disposal. Unity game development is one of those. 

Creating A Multiplayer Game With Unity

If you are looking for a simplified way to create a multiplayer game through Unity, look no further. However, before taking a look at the steps, make sure you have a firm grasp on: 

  • C# programming
  • How to use the Unity Editor, import assets, create prefabs and include components

Creating a demo with a multiplayer space shooter that allows multiple players to join the game and shoot randomly spawned enemies includes many steps like: 

  • Create a project and Import assets
  • Create a background canvas
  • Create a network manager
  • Ship movement
  • Shooting bullets
  • Adding enemies

Create A Project and Import Assets

The first thing you ought to do is create a new Unity project and import all the sprites you can get access via the source code. First, create a folder and copy all the sprites to this folder. Then, import them. Some sprites are in sprite sheets, in which case you will have to set the sprite mode as multiple, open the editor, and slice them. You will have to download the source code files.

Create A Background Canvas

You need to create a background canvas to display the background image. For this, create a new image in the hierarchy. In the background canvas, be sure to set the ‘Render Mode’ to screen space camera, for which you must attach your main camera. After this, set the UI scale mode in alignment with the screen size to ensure the canvas appears in the background and not in front of the objects. Set the source image to space and you should find the space background in the game. 

Create A Network Manager

If you want a multiplayer game to work, you need to have a game object with a network manager and networkmanagerHUD components. This object facilitates the connection, management, and synchronization of different clients in the game. 

This is how Unity for game development works: 

  • As a player, you can start the game as a host. Select the LAN host. 
  • Other players may connect to this host as clients through LAN client 

If you want to test the game, you will have to open two instances, as the host and as the client. However, the Unity editor does not allow you to open two instances of the game, which means you will have to build the game and run the first instance through an executable file. 

To do this, head to File ? Build Settings, and add the game scene. After this, File ? Build & Run. Once you do this, enter ‘Play Mode’ to run the second instance of the game. 

You can make a faster selection based on various factors, such as server locations, value for money, packages, and speed by going through the information provided under each of the best Rust server host providers reviewed in this tutorial.

Ship Movement

At this point, you probably have the network manager in place. Now you have to create the game objects that the network manager will manage. The first game object to create is the player ship, which will currently only move horizontally. The network manager will update its position. Be sure to make this game object a prefab.  

For a game object to be managed by the network manager, you need to include a network identify component. Additionally, you will have to include RigidBody2D and BoxCollider2D for movement and collisions, and MoveShip script for the speed parameter.  Before you start playing the game, you will need to specify that the ship prefab is the player prefab. 

To spawn predefined positions, you will have to create a new game object to be the spawn position. Then, you add the network start position component to it. Once you do this, you must specify how the network manager will use the positions you assign. The two options you can use are: Random and Round Robin. 

Shooting Bullets

At this point, you give the ships the ability to shoot bullets, and these bullets must be synchronized to all instances of the game. Start by creating the bullet prefab. To manage this object in the network, include the network identify and network transform components. After you create the bullet, you do not need to set its position using the network. However, be sure to change the network send rate in the network transform section. 

To bring in the speed and collision parameters, you will need to add a RigidBody2D and CircleCollider2D to the prefab. 

Adding Enemies

You begin by adding an enemy prefab, for which you need to create a new game object called enemy and turn it into a prefab, just as you would for ships. For movements and collisions, be sure to add a RigidBody2D and BoxCollider2D. 

For it to be controlled by the network manager, you will need to add the network identify and network transform components.Create a new game object called enemy spawner with a network identity. However, this must exist only in the server. As far as taking damage goes, you will need a script called ‘receive damage,’ with parameters like ‘max health’, ‘enemy tag’, and ‘destroy on death.’ 

 

The script looks like this – 

 

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using Mirror;

 

public class ReceiveDamage : NetworkBehaviour

{

    [SerializeField]

    private int maxHealth = 10;

 

    [SyncVar]

    private int currentHealth;

 

    [SerializeField]

    private string enemyTag;

 

    [SerializeField]

    private bool destroyOnDeath;

 

    private Vector2 initialPosition;

 

    // Use this for initialization

    void Start ()

    {

        this.currentHealth = this.maxHealth;

        this.initialPosition = this.transform.position;

    }

 

    void OnTriggerEnter2D (Collider2D collider)

    {

        if(collider.tag == this.enemyTag)

        {

            this.TakeDamage(1);

            Destroy(collider.gameObject);

        }

    }

 

    void TakeDamage (int amount)

    {

        if(this.isServer)

        {

            this.currentHealth -= amount;

 

            if(this.currentHealth <= 0)

            {

                if(this.destroyOnDeath)

                {

                    Destroy(this.gameObject);

                }

                else

                {

                    this.currentHealth = this.maxHealth;

                    RpcRespawn();

                }

            }

        }

    }

 

    [ClientRpc]

    void RpcRespawn ()

    {

        this.transform.position = this.initialPosition;

    }

}

 

Wrapping Up

Here’s the gist on how to go about creating a simple multiplayer shooter using Unity game development. As you can see, the tools you have today are immensely powerful, and can help you create incredibly realistic games. However, there’s always room to hire a game developer from leading mobile app development companies

Subscribe

Related articles

Strategic Approach Balloon Crash Game

Introduction to Balloon Crash In the intriguing world of digital...

Supercharging Security: The Pivotal Role of Embedded Single-Board Computers

In the rapidly evolving landscape of security technology, the...

Top Tips for Choosing the Right Emergency Plumbing Service

When a plumbing emergency strikes, the stress and chaos...

Smart Storage Mastery: Elevating Kitchens and Bathrooms

In the quest for a harmonious and efficient home,...

Transforming Your Home: A Comprehensive Guide to Upgrades

Enhancing Your Walls: Tips and Trends in Drywall Installation When...

The Art of Lighting Design: Why You Need to Get It Right

Lighting design plays a pivotal role in both residential...

Does Laser Marking Use Ink?

Laser marking is an advanced technology that offers an...
Rahul
Rahul
C-Incognito

LEAVE A REPLY

Please enter your comment!
Please enter your name here