Unity 2D Game Development, Implementing Multiplayer Features: How to Add Simple Multiplayer Features to a 2D Game.

Introduction

In this course, we will learn how to add simple multiplayer features to a 2D game using the Unity engine.
Multiplayer functionality greatly increases the fun of the game and provides opportunities to enjoy it with friends.
Additionally, through the process of implementing multiplayer, you will understand concepts such as networking and data synchronization.

1. Preparing the Game

First, let’s conceptualize the game you want to create.
For example, a simple 2D platformer.
Players can compete against each other to earn points or achieve objectives.

1.1 Creating a Unity Project

After launching Unity, create a new 2D project.
Name the project ‘Multiplayer2DGame’ and select the default template.

2. Setting Up Photon Unity Networking (PUN)

We will use a library called Photon Unity Networking (PUN) to implement multiplayer features.
PUN is a tool that simplifies multiplayer game development in Unity.

2.1 Installing PUN

3. Implementing Basic Player

Now let’s create a basic player character. The player should be able to interact with other users.
We need to create a player prefab and set up network synchronization using PUN.

3.1 Creating a Player Prefab

  1. Create the player character using a 2D sprite. For example, let’s create a circular sprite.
  2. Create a new Empty GameObject and name it ‘Player.’
  3. Add Circle Collider 2D and Rigidbody 2D components to the Player GameObject.
  4. Now, make the Player a Prefab and save it in the Assets folder.

3.2 Integrating with PUN

Create a player script to integrate PUN functionalities. Let’s write the player script using the code below.

using UnityEngine;
using Photon.Pun;

public class PlayerController : MonoBehaviourPunCallbacks
{
    public float moveSpeed = 5f;

    void Update()
    {
        if (photonView.IsMine)
        {
            Move();
        }
    }

    void Move()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        Vector3 moveDirection = new Vector3(horizontal, vertical, 0).normalized;
        transform.position += moveDirection * moveSpeed * Time.deltaTime;
    }
}

3.3 Player Spawning

Next, we need to add functionality to spawn the player when the game starts.
Add the code below to a new script called GameManager.

using UnityEngine;
using Photon.Pun;

public class GameManager : MonoBehaviourPunCallbacks
{
    void Start()
    {
        PhotonNetwork.ConnectUsingSettings();
    }

    public override void OnConnectedToMaster()
    {
        PhotonNetwork.JoinLobby();
    }

    public override void OnJoinedLobby()
    {
        PhotonNetwork.LoadLevel("GameScene");
    }

    public override void OnJoinedRoom()
    {
        PhotonNetwork.Instantiate("Player", Vector3.zero, Quaternion.identity, 0);
    }
}

4. Implementing Game Lobby

A multiplayer game requires a lobby. In the lobby, players can wait and start the game.
Let’s move on to creating the lobby UI.

4.1 Setting Up UI

We will use Unity’s UI system to create the UI.
Create a Canvas and add button and text UI elements.
Buttons can perform functions like ‘Create Room’ and ‘Join Room.’

4.2 Adding Room Creation and Joining Code

using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;

public class LobbyManager : MonoBehaviourPunCallbacks
{
    public InputField roomNameInputField;
    
    public void CreateRoom()
    {
        string roomName = roomNameInputField.text;
        RoomOptions roomOptions = new RoomOptions() { MaxPlayers = 4 };
        PhotonNetwork.CreateRoom(roomName, roomOptions);
    }

    public void JoinRoom()
    {
        string roomName = roomNameInputField.text;
        PhotonNetwork.JoinRoom(roomName);
    }

    public override void OnCreatedRoom()
    {
        Debug.Log("Room has been created.");
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("Joined the room.");
    }
}

5. Network Synchronization

Now we will implement network synchronization so that multiple players can connect to the game and interact with each other.
We will synchronize player actions using Photon.

5.1 Using RPC

We will use RPC (Remote Procedure Call) to synchronize player actions (e.g., jumping, attacking, etc.).
Below is the code that will be used when the player jumps.

using Photon.Pun;

[PunRPC]
public void Jump()
{
    if (IsGrounded())
    {
        GetComponent().AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }
}

6. Implementing Scoring System

In cases where multiple players compete against each other, a scoring system is needed.
This system is responsible for storing and displaying players’ scores.

6.1 Creating Score Database Class

using UnityEngine;

[System.Serializable]
public class PlayerScore
{
    public string playerName;
    public int score;
}

public class ScoreManager : MonoBehaviour
{
    public List scores = new List();
}

6.2 Displaying Scores

In order to display the scores in the UI, we will create a Text UI element and make a script that updates each player’s score.

using UnityEngine;
using UnityEngine.UI;

public class ScoreDisplay : MonoBehaviour
{
    public Text scoreText;

    public void UpdateScore(PlayerScore playerScore)
    {
        scoreText.text = playerScore.playerName + ": " + playerScore.score;
    }
}

7. Testing and Deployment

After implementing all the features, we will perform testing.
Use PUN’s Premier Servers to run multiple clients and check progress and bugs.
After testing is complete, the game can be built and distributed to users.

Conclusion

In this course, we learned how to add multiplayer features to a 2D game in Unity.
Utilizing Photon Unity Networking (PUN), we were able to facilitate interactions and data synchronization among players.
Developing a multiplayer game is not easy, but it is a very interesting and rewarding task.
I hope you can add various features and create your own game in your personal style.
Stay tuned for more Unity-related courses!