Unity uses PhotonEngine to realize multiplayer online game development (2)

Unity uses PhotonEngine to realize multiplayer online game development (2)

The previous article was written in a hurry because the Mac was out of power. The logic may not be very good, and some instructions are missing. Let me add something first:

The correct steps to apply for free photon cloud should be to first register an account on the global official website, then create a photon cloud application, get an APP ID, and then use this APP ID to go to the Chinese website to apply. When applying, you should also pay attention to selecting Photon as the APP ID type. PUN
Insert image description here

OK, now start to achieve the goals mentioned in the previous article one by one:

  • Search for the Load Balancing Client script in unity and open it.
    Insert image description here
    Find the NameServerHost. It was originally http://ns.exitgame.com. Change it to http://ns.photonengine.cn and save it.
    Insert image description here
    Then go
    Insert image description here
    to Fixed Region and fill in cn.
  • Construction of the initial scene and writing of the link network script:
    Create a button button and a script named NetworkingManager, and then create an empty object to mount the script, also named NetworkingManager.
    Insert image description here
    Insert image description here
  • Scripting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//引入命名空间
using Photon.Pun;
using Photon.Realtime;

//让脚本继承MonoBehaviourPunCallbacks类,这个类是关于回调函数的
public class NetworkingManager : MonoBehaviourPunCallbacks
{
    
    
    [SerializeField]
    private int sceneIndex;
    //当按钮被点击的时候判断一下是否与服务器链接,如果链接成功就加入房间,否则开始链接。
    public void ClickBtn()
    {
    
    
        if (PhotonNetwork.IsConnected)
        {
    
    
            PhotonNetwork.JoinRandomRoom();
        }
        else
        {
    
    
            PhotonNetwork.ConnectUsingSettings();
        }
    }
    //尝试与主服务器进行链接时调用
    public override void OnConnectedToMaster()
    {
    
    
        PhotonNetwork.JoinRandomRoom();
    }
    //当链接成功时调用
    public override void OnConnected()
    {
    
    
        Debug.Log("------链接成功------");
    }
    //当链接失败的时候
    public override void OnDisconnected(DisconnectCause cause)
    {
    
    
        Debug.Log("------链接失败------");
    }
    //当加入大厅成功的时候
    public override void OnJoinedLobby()
    {
    
    
        Debug.Log("------加入大厅成功------");
    }
    //加入房间失败的时候调用,加入房间失败,并创建房间,可容纳最大人数为5人
    public override void OnJoinRandomFailed(short returnCode, string message)
    {
    
    
        Debug.Log("------加入房间失败------");
        Debug.Log("------建立新房间,最大可容纳5人------");
        PhotonNetwork.CreateRoom("RoomName",new RoomOptions {
    
     MaxPlayers = 5 });
    }
    //创建房间成功
    public override void OnCreatedRoom()
    {
    
    
        Debug.Log("------创建房间成功------");
    }
    //创建房间失败
    public override void OnCreateRoomFailed(short returnCode, string message)
    {
    
    
        Debug.Log("------创建房间失败------");
    }
    //加入房间成功,并跳转场景至游戏界面
    public override void OnJoinedRoom()
    {
    
    
        Debug.Log("------加入房间成功------");
        PhotonNetwork.LoadLevel(sceneIndex);
    }
    //离开房间时调用
    public override void OnLeftRoom()
    {
    
    
        Debug.Log("------离开房间------");
    }
    //离开大厅时调用
    public override void OnLeftLobby()
    {
    
    
        Debug.Log("------离开大厅------");
    }
}

The comments of each callback function have been written in detail, so I won’t introduce them one by one. After the writing is completed, add the method ClickBtn() that will be triggered after clicking on the button. You
can start running and then click the connection to test. The following picture is the result of my test run.
Insert image description here

  • After the scene jumps, make a simple interaction (WASD keys control player movement).
    Although it is simple here, it is worth noting that because we need to synchronize other players in the network, we need to add two when making prefabs like players. There are two components, namely PhotonView and PhotonTransformView . Also, we need to put the prefab in a folder called Resource so that the engine can find our player based on this directory.
    Insert image description here
    I wrote the interactive code on an empty object named GameManager.
    Insert image description here
    Insert image description here
    The code is as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//引入命名空间
using Photon.Pun;

public class GameManager : MonoBehaviourPun  //继承MonoBehaviourPun类
{
    
    
    [SerializeField]
    private GameObject Player;
    private GameObject go = null;

    //游戏一开始就把玩家实例话出来
    private void Awake()
    {
    
    
        go = PhotonNetwork.Instantiate(Player.name, Vector3.zero, Quaternion.identity);   
    }
    /// <summary>
    /// WASD键跟新player的位置信息
    /// </summary>
    private void Update()
    {
    
    
        go.transform.position += Input.GetAxis("Horizontal") * Vector3.right * 0.4f;
        go.transform.position += Input.GetAxis("Vertical") * Vector3.forward * 0.4f;

    }
}
  • Export save and run
    Insert image description here

Guess you like

Origin blog.csdn.net/qq_41294510/article/details/131511470