Build Unity Mobile Online Multiplayer Game using Photon PUN
Build Unity Mobile Online Multiplayer Game using Photon PUN
Learn Multiplayer Mobile Game Development | Create Unity3d iOS and Android Battle Royale Game like FREE FIRE and PUBG
Enroll Now
Building an online multiplayer game can be a complex task, but using a powerful tool like Photon Unity Networking (PUN) makes the process significantly more manageable. PUN is a real-time multiplayer framework for Unity that simplifies connecting players, syncing objects, and handling networked game events. It abstracts the complexity of network programming, letting developers focus on gameplay logic. In this tutorial, we will walk through the steps to create a basic multiplayer game for mobile platforms using Unity and Photon PUN.
Setting up Unity for Multiplayer Development
Step 1: Installing Unity
To begin building a multiplayer game, you need the Unity Game Engine. If you haven't already, download and install the latest version of Unity from the official website. Make sure to select the appropriate modules for mobile development, such as Android or iOS support, based on your target platform.
Step 2: Creating a New Unity Project
Once Unity is installed, launch the editor and create a new project. You can name it something descriptive like "MobileMultiplayerGame". Choose 2D or 3D, depending on your game's perspective.
Step 3: Installing Photon PUN
Photon PUN is available as a package that you can import into your Unity project. Here’s how you can do it:
- Go to Window > Asset Store or open the Unity Asset Store in your browser.
- Search for Photon PUN 2 and click Add to My Assets.
- In Unity, go to Window > Package Manager, click on the My Assets tab, and locate Photon PUN. Download and import it into your project.
Step 4: Setting Up Photon
To use Photon, you need to create an account on the Photon website. Once you’ve registered, follow these steps to integrate Photon into Unity:
- Log in to the Photon dashboard and create a new Photon application.
- Copy the App ID that Photon provides.
- Back in Unity, navigate to Window > Photon Unity Networking > PUN Wizard and paste the App ID into the appropriate field. You can now connect your Unity game to the Photon servers.
Basic Multiplayer Game Concept
For this tutorial, we will build a simple multiplayer game where players can join a room, control their characters, and interact with each other in real-time. We will create a basic scene with a couple of players who can move around and see each other’s movements.
Step-by-Step Guide to Building the Game
Step 1: Create the Game Scene
Create a new scene in Unity named "MultiplayerScene". In this scene, we will set up the basic game environment where players can move and interact with each other. For simplicity, let’s add a Plane as the ground and some 3D cubes or 2D sprites as obstacles.
Step 2: Player Prefab
Now, we need to create a player that will be instantiated for each user who joins the game. Here's how you can create a player prefab:
- Create a new empty GameObject and name it "Player".
- Add a Rigidbody and a Collider (either BoxCollider or CharacterController based on your player model).
- Attach a simple PlayerMovement script to handle the player's movement.
Here’s an example of a basic movement script:
csharpusing UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0, moveVertical);
transform.Translate(movement * speed * Time.deltaTime, Space.World);
}
}
Step 3: Photon Player Instantiation
For multiplayer games, each player will instantiate their own character when they join a room. However, other players should also see these characters. Photon makes this easy with the PhotonNetwork.Instantiate method.
- Convert the Player GameObject into a Prefab by dragging it to the project window.
- Attach a PhotonView component to the player prefab to enable synchronization.
- Use the following code to instantiate the player when a player joins the game:
csharpusing Photon.Pun;
using UnityEngine;
public class GameManager : MonoBehaviourPunCallbacks
{
public GameObject playerPrefab;
void Start()
{
if (PhotonNetwork.IsConnectedAndReady)
{
PhotonNetwork.Instantiate(playerPrefab.name, new Vector3(0, 0, 0), Quaternion.identity);
}
}
}
This code ensures that when a player connects to the Photon network and joins a room, a new player object is instantiated in the game world for them.
Step 4: Network Synchronization
To ensure that each player’s movements are visible to others in the room, you need to synchronize the player’s position across the network. Photon provides a tool called PhotonTransformView for this purpose.
- Select the Player Prefab.
- Attach the PhotonTransformView component to it.
- Configure the PhotonTransformView to synchronize the position and rotation of the player.
This will allow the player’s movements to be shared in real-time across all connected players.
Step 5: Joining and Creating Rooms
Players need to join rooms to play together. Here’s how to implement room creation and joining:
- Create a simple UI with buttons for creating and joining rooms. You can use Unity’s UI system to create buttons and text fields.
- Add a script to handle room creation and joining using Photon’s Lobby system.
Here’s a basic script for room management:
csharpusing Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.UI;
public class RoomManager : MonoBehaviourPunCallbacks
{
public InputField roomNameInputField;
public Text feedbackText;
public void CreateRoom()
{
string roomName = roomNameInputField.text;
if (string.IsNullOrEmpty(roomName))
{
feedbackText.text = "Room name cannot be empty!";
return;
}
PhotonNetwork.CreateRoom(roomName, new RoomOptions { MaxPlayers = 4 });
}
public void JoinRoom()
{
string roomName = roomNameInputField.text;
if (string.IsNullOrEmpty(roomName))
{
feedbackText.text = "Room name cannot be empty!";
return;
}
PhotonNetwork.JoinRoom(roomName);
}
public override void OnJoinedRoom()
{
PhotonNetwork.LoadLevel("MultiplayerScene");
}
public override void OnJoinRoomFailed(short returnCode, string message)
{
feedbackText.text = "Failed to join room: " + message;
}
}
This script allows players to create or join rooms using the UI. When a player successfully joins a room, they are taken to the MultiplayerScene where the game takes place.
Step 6: Syncing Player Actions
Besides position synchronization, you may want to sync other player actions, such as shooting or jumping. You can achieve this by using RPCs (Remote Procedure Calls) in Photon.
Here’s an example of how you might sync a shooting action:
csharp[PunRPC]
void Shoot()
{
// Shooting logic here
Debug.Log("Player shot!");
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
photonView.RPC("Shoot", RpcTarget.All);
}
}
The PunRPC attribute allows this method to be called on all clients when a player shoots.
Final Steps: Building for Mobile
Once you have your multiplayer game running in Unity, you can build and deploy it to mobile platforms. Here’s a brief overview of the build process:
- Go to File > Build Settings.
- Select either Android or iOS as your target platform and click Switch Platform.
- Ensure that your project settings (graphics, resolution, etc.) are optimized for mobile devices.
- Build and run the game on a mobile device or emulator.
Conclusion
Congratulations! You’ve now created a basic mobile multiplayer game using Unity and Photon PUN. While this tutorial covers the essential steps, there is much more you can do with Photon, such as adding voice chat, in-game chat systems, and advanced matchmaking.
Post a Comment for "Build Unity Mobile Online Multiplayer Game using Photon PUN"