Back To Home

Photon

6-04-2024

Ready, Set, Network! Delving into Essential Photon Components for Your Games

"This is a continuation of part 1. In this part, we'll delve deeper into the the important components of Photon."

1. PhotonView :

  1. The PhotonView component is one of the most critical components in Photon. It is responsible for synchronizing GameObjects across the network.

  2. Attach the PhotonView component to any GameObject that you want to synchronize between players.

  3. Each GameObject with a PhotonView component is assigned a unique ID by Photon, allowing it to be identified and synchronized correctly across the network.

  4. The PhotonView component provides methods for sending RPCs (Remote Procedure Calls) to other players, allowing you to execute code on remote clients.

2. PhotonTransformView :

  1. The PhotonTransformView component is used to synchronize the position, rotation, and scale of GameObjects across the network.

  2. When attached to a GameObject with a PhotonView component, the PhotonTransformView component automatically handles the synchronization of transform properties.

  3. It provides options for interpolation and extrapolation to smooth out movement and reduce perceived latency.

3. PhotonAnimatorView :

  1. The PhotonAnimatorView component is used to synchronize animations across the network.

  2. When attached to a GameObject with a PhotonView component, it synchronizes the state and parameters of the Animator component across all connected clients.

  3. It ensures that all players see the same animations being played on remote characters, maintaining consistency in the game world.

4. PhotonRigidbodyView :

  1. The PhotonRigidbodyView component synchronizes Rigidbody physics properties (such as velocity, angular velocity, etc.) of GameObjects across the network.

  2. It ensures that physics interactions are consistent among all players in the game.

5. PhotonNetwork :

  1. The PhotonNetwork class provides static methods for managing network connections and interactions in your game.

  2. It handles tasks such as connecting to the Photon servers, creating and joining rooms, and sending RPCs.

  3. Use PhotonNetwork.Instantiate() to instantiate GameObjects across the network. This method automatically synchronizes instantiated GameObjects across all connected clients.

6. PhotonLobby :

  1. The Photon Lobby is a virtual waiting room where players can meet, create, and join rooms before entering the main gameplay.

  2. It allows players to browse available rooms, chat with other players, and manage their multiplayer experience.

  3. You can customize the lobby's appearance and behavior using Unity's UI system and Photon's lobby-related APIs.

7. PhotonRoom :

  1. A Photon Room is a virtual space where players interact and play the game together.

  2. Players can create their rooms or join existing ones based on various criteria such as room name, size, or custom properties.

  3. Once inside a room, players can communicate with each other, synchronize gameplay data, and participate in multiplayer gameplay sessions.

8. PhotonMessageInfo :

  1. The PhotonMessageInfo class provides information about a message received over the network, such as the sender's PhotonPlayer ID, timestamp, and other metadata.

  2. It's often used in conjunction with RPCs to determine who sent a particular message and react accordingly.

9. PhotonVoiceView :

  1. The PhotonVoiceView component is used for real-time voice communication in multiplayer games.

  2. It allows players to speak to each other using their microphones and hear other players' voices.

  3. This component handles the transmission and synchronization of voice data across the network.

10. PhotonRoomProperties :

  1. PhotonRoomProperties is used to define custom properties for Photon rooms.

  2. These properties can be set by the room creator and used for various purposes, such as defining game settings, matchmaking criteria, or room-specific rules.


Understanding these components will provide you with a solid foundation for developing multiplayer games with Photon. Each component plays a crucial role in ensuring smooth and reliable network synchronization, enabling engaging multiplayer experiences for players. Now that we have a good grasp of these components, we can proceed with writing code to implement multiplayer functionality in our game.


Understanding MonoBehaviourPunCallbacks in Photon :

  1. NOTE : Our script will inherit MonoBehaviourPunCallbacks instead of MonoBehaviour which allows us to easily handle Photon-related events and callbacks.

  2. MonoBehaviourPunCallbacks is a class provided by the Photon Unity Networking (PUN) package that extends MonoBehaviour.

  3. It contains a set of pre-defined methods that are automatically called by the PUN framework in response to various network events, such as connecting to the Photon server, joining a room, creating a room, etc.

  4. By inheriting from MonoBehaviourPunCallbacks, our script gains access to these callback methods, allowing us to easily react to Photon-related events without having to manually manage event subscriptions or callbacks.

code :

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

public class PhotonManager : MonoBehaviourPunCallbacks
{

    private string gameVersion = "1"; // Version of the game
    private int maxPlayers = 4; // Maximum number of players in a room

    void Start()
    {
        Connect();

        // Automatically sync scene changes for all clients in the same room
        PhotonNetwork.AutomaticallySyncScene = true;
    }

    // Method to connect to Photon server
    public void Connect()
    {
        // Check if already connected
        if (!PhotonNetwork.IsConnected)
        {
            // Connect to Photon server using settings from the PhotonServerSettings asset
            PhotonNetwork.ConnectUsingSettings();
            PhotonNetwork.GameVersion = gameVersion; // Set game version for matchmaking (optional)
        }
        else
        {
              // If already connected, check if the player is in a lobby
            if (PhotonNetwork.InLobby)
            {
                // If in a lobby, no action needed as the player is already where they should be
                Debug.Log("Already in lobby.");
            }
            else
            {
                // If not in a lobby, join the default lobby
                PhotonNetwork.JoinLobby();
            }
        }
    }



    // Callback triggered when connection to Photon server is established
    public override void OnConnectedToMaster()
    {
        Debug.Log("Connected to Photon server!");
        
        // After connecting, join the default lobby
        PhotonNetwork.JoinLobby();
    }


    // Callback triggered when failed to connect to Photon server
    public override void OnDisconnected(DisconnectCause cause)
    {
        Debug.LogWarning($"Disconnected from Photon server due to: {cause}");
    }



    // Callback triggered when joined the lobby successfully
    public override void OnJoinedLobby()
    {
        Debug.Log("Joined Photon lobby!");
        
        // Create or join a room when joined the lobby
        CreateOrJoinRoom();
    }



    // Method to create or join a room
    void CreateOrJoinRoom()
    {
        if (PhotonNetwork.CountOfRooms == 0)
        {
            // If no rooms available, create a new room
            // Generate a unique room name using a random string
            string roomName = "Room_" + Random.Range(1000, 10000);

            // Create a new room with the generated name and set max players
            PhotonNetwork.CreateRoom(roomName, new RoomOptions { MaxPlayers = maxPlayers });

        }
        else
        {
            // If rooms are available, join the first one
            PhotonNetwork.JoinRandomRoom();
        }
    }



    // Callback triggered when successfully created a room
    public override void OnCreatedRoom()
    {
        Debug.Log("Room created!");
    }



    // Callback triggered when failed to create a room
    public override void OnCreateRoomFailed(short returnCode, string message)
    {
        Debug.LogWarning($"Failed to create room: {message}");
        
        // Retry creating a room or join another room
        CreateOrJoinRoom();
    }



    // Callback triggered when successfully joined a room
    public override void OnJoinedRoom()
    {
        Debug.Log("Joined room!");

        // Load the game scene when joined a room
        PhotonNetwork.LoadLevel("GameScene");
    }



    // Callback triggered when failed to join a room
    public override void OnJoinRoomFailed(short returnCode, string message)
    {
        Debug.LogWarning($"Failed to join room: {message}");
        
        // Retry joining another room
        CreateOrJoinRoom();
    }


      // Callback triggered when a remote player joins the room
    public override void OnPlayerEnteredRoom(Player newPlayer)
    {
        Debug.Log($"Player {newPlayer.NickName} joined the room.");
    }



    // Callback triggered when a remote player leaves the room
    public override void OnPlayerLeftRoom(Player otherPlayer)
    {
        Debug.Log($"Player {otherPlayer.NickName} left the room.");
    }



    // Callback triggered when the local player leaves the room
    public override void OnLeftRoom()
    {
        Debug.Log("Left room.");
    }

}

  1. This code sets up a PhotonManager script that connects to the Photon server when the game starts (OnConnectedToMaster). Once connected, it joins the default lobby (OnJoinedLobby).

  2. Upon joining the lobby, it creates or joins a room (CreateOrJoinRoom). If no rooms are available, it creates a new room, otherwise, it joins a random room.

  3. Callbacks are provided for various scenarios such as successful room creation (OnCreatedRoom), failed room creation (OnCreateRoomFailed), successful room join (OnJoinedRoom), failed room join (OnJoinRoomFailed) etc. In case of failures, appropriate retry mechanisms are included.

  4. This should give you a basic understanding of how to handle Photon connections, lobby operations, and room creation/joining in your Unity game. Feel free to customize and expand upon this code to suit your specific multiplayer game requirements!


Please read => Part 3 for further exploration of Photon Unity Networking features and implementation details.


I hope you found this blog post enjoyable!


More Blogs

See All