服务器端创建完成后,接下来开始创建我们的客户端程序,使用的unity3D版本为5.5.2f1。
一、新建工程
在unity中新建一个工程,名称为MyGameServer,创建好工程后新建三个文件夹Plugins(unity中存放外来第三方插件的文件夹) ,Scenes(存放有关的游戏场景),Scripts(存放脚本)。在Plugins添加lib文件夹下的Photon3Unity3D.dll文件。在Hierarchy视窗中右击Create Empty 创建一个空游戏物体并命名为GamePhotonEngine,新建GamePhotonEngine.cs脚本并挂载在该游戏物体上。
二、跟服务器端建立连接
为GamePhotonEngine脚本添加IPhotonPeerListener监听,实现内容入下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ExitGames.Client.Photon;
public class GamePhotonEngine : MonoBehaviour ,IPhotonPeerListener{
public static GamePhotonEngine Instance; // 全局单例模式
private static PhotonPeer peer;
public static PhotonPeer Peer
{
get
{
return peer;
}
}
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
else if (Instance != this)
{
Destroy(this.gameObject); return;//所有场景只留一个PhotonEngine 删除多余的
}
}
// Use this for initialization
void Start()
{
//通过Listener接收服务器端的响应
peer = new PhotonPeer(this, ConnectionProtocol.Udp);//Udp又快又稳
peer.Connect("127.0.0.1:5055", "MyGame");//连接服务器 发起连接 //127.0.0.1本机地址 5055端口号和photon配置文件里的一样,MyGame 要连接的服务器名
}
// Update is called once per frame
void Update () {
peer.Service(); //发起请求 无论什么状态下
}
public void DebugReturn(DebugLevel level, string message)
{
}
//服务器端向客户端发起数据的时候
public void OnEvent(EventData eventData)
{
}
//客户端向服务器发起一个请求以后服务器处理完以后 就会给客户端一个响应
public</