游戏服务器搭建4(借助NHibernate)

101 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第2天,点击查看活动详情

4、搭建Unity客户端

①创建Unity工程,新建Plugins文件夹,导入包Photon3Unity3D.dll,文件包在photon的lib里。

②新建PhotonEngine.cs代码

【PhotonEngine.cs客户端代码】

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ExitGames.Client.Photon;

public class PhotonEngine : MonoBehaviour,IPhotonPeerListener
{
    private static PhotonEngine Instance;
    private PhotonPeer peer;

    public void DebugReturn(DebugLevel level, string message)
    {
        throw new System.NotImplementedException();
    }

    public void OnEvent(EventData eventData)
    {
        throw new System.NotImplementedException();
    }

    public void OnOperationResponse(OperationResponse operationResponse)
    {
        throw new System.NotImplementedException();
    }

    public void OnStatusChanged(StatusCode statusCode)
    {
        throw new System.NotImplementedException();
    }

    void Awake() 
    {
        if (Instance == null)//空则创建
        {
            Instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else if (Instance!=this)//有则销毁 
        {
            Destroy(this.gameObject);
            return;
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        //通过Listener接收服务器的响应
        peer = new PhotonPeer(this, ConnectionProtocol.Udp);//使用UDP协议
        peer.Connect("127.0.0.1:5055","MyGame1");//在PhotonServer中查看相关配置情况,指定端口号以及应用名称

    }

    // Update is called once per frame
    void Update()
    {
         peer.Service();
    }
    void OnDestroy() 
    {
        if (peer != null && peer.PeerState == PeerStateValue.Connected) 
        {
            peer.Disconnect();
        }
    }
}

客户端添加成功后,在Unity中绑定新的Test.cs代码实现实时的请求响应

【Test.cs代码】


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            SendRequest();
        }
    }
    void SendRequest() 
    {
        Dictionary<byte, object> data = new Dictionary<byte, object>();
        PhotonEngine.Peer.OpCustom(1,data,true);
    }
}

请求响应后日志内容实时更新

image.png

连接响应请求示意图 image.png