Unity3D 客户端编程

时间:2022-09-02 17:00:29

Photon Server 和 Unity3D 数据交互:

Photon Server 服务端编程

Unity3D 客户端编程

VS2017 之 MYSQL实体数据模型

1:打开unity新建新项目,并引入Photon3Unity3D.dll到plugins文件中。

Unity3D 客户端编程

2、新建一个空物体,添加两个脚本文件。

Unity3D 客户端编程

3、编辑Photon Engine。

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ExitGames.Client.Photon;
using System; public class PhotonEngine : MonoBehaviour, IPhotonPeerListener
{
//单例模式
private static PhotonEngine instance;
private static PhotonPeer peer; public static PhotonPeer Peer
{
get
{
return peer;
}
} private void Awake()
{
if (instance == null)
{
instance = this;
//不需要销毁
DontDestroyOnLoad(this.gameObject);
}
else if (instance != this)
{
Destroy(this.gameObject);
return;
}
}
private void Start()
{
try
{
//PhotonPeer实例化时需要监听类和连接协议。所以该类继承IPhotonPeerListener接口实现监听
peer = new PhotonPeer(this, ConnectionProtocol.Udp);
peer.Connect("122.237.104.105:5055", "Mygame1");
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
} private void Update()
{
//时刻发送请求
peer.Service();
} private void OnDestroy()
{
if (peer != null && peer.PeerState == PeerStateValue.Connected)
{
peer.Disconnect();
}
} public void DebugReturn(DebugLevel level, string message)
{ } public void OnEvent(EventData eventData)
{
switch (eventData.Code)
{
case :
Dictionary<byte, object> di = eventData.Parameters;
object i;
di.TryGetValue(, out i);
Debug.Log("收到服务器消息" + i.ToString());
break;
case :
break;
default:
break;
} } public void OnOperationResponse(OperationResponse operationResponse)
{
switch (operationResponse.OperationCode)
{
case :
Debug.Log("收到服务器响应!。。。。。");
Dictionary<byte, object> d = operationResponse.Parameters;
object i, j;
d.TryGetValue(, out i);
d.TryGetValue(, out j);
Debug.Log("收到服务器返回" + i.ToString() + j.ToString());
break;
default:
break;
}
} public void OnStatusChanged(StatusCode statusCode)
{
Debug.Log(statusCode);
}
}

4、text类用来发送请求。

 using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class text : MonoBehaviour { private void Update()
{
if (Input.GetMouseButtonDown())
{
SendRequest();
}
} private void SendRequest()
{
Dictionary<byte, object> date = new Dictionary<byte, object>();
date.Add(, );
date.Add(,"sdgsdgdsfg");
PhotonEngine.Peer.OpCustom(, date, true);
}
}

5、运行结果。先启动服务器在启动客户端,鼠标左点击发送请求。

服务端:

Unity3D 客户端编程

客户端:

Unity3D 客户端编程

下载地址:https://gitee.com/today6/unity