Photon
1.0 Photon搭建
(2条消息) 【Unity3D】Photon环境搭建_photon框架_little_fat_sheep的博客-CSDN博客
2.0 连接云服务器
主要代码 :PhotonNetwork.ConnectUsingSettings();
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PhotonDemo : MonoBehaviour
{
public GUISkin skin;//设置字体
#region GUI Fields
private List<string> photonState;
#endregion
/// <summary>
/// 标记上一次的状态
/// </summary>
private ClientState previousState;
private void Awake()
{
photonState = new List<string>();
}
private void Start()
{
//链接Photon Cloud
bool connectResult = PhotonNetwork.ConnectUsingSettings();
//初始状态
previousState = PhotonNetwork.NetworkClientState;
photonState.Add(previousState.ToString());
}
private void Update()
{
if (PhotonNetwork.NetworkClientState != previousState)
{
//如果当前状态更新,则添加到字典
photonState.Add(previousState.ToString());
//更新previous
previousState = PhotonNetwork.NetworkClientState;
}
}
void OnGUI()
{
GUI.skin = skin;
for (int i = 0; i < photonState.Count; i++)
{
GUILayout.Label(photonState[i]);
}
}
}
链接成功。
3.0 创建房间
状态:ClientState.ConnectedToMasterServer
创建房间 : PhotonNetwork.CreateRoom(roomName);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PhotonDemo : MonoBehaviour
{
public GUISkin skin;
#region GUI Fields
private List<string> photonState;
#endregion
/// <summary>
/// 标记上一次的状态
/// </summary>
private ClientState previousState;
private string roomName = "room007";
private string roomMaxCount = "2";
private void Awake()
{
photonState = new List<string>();
}
private void Start()
{
//初始状态
previousState = PhotonNetwork.NetworkClientState;
photonState.Add(previousState.ToString());
}
private void Update()
{
if (PhotonNetwork.NetworkClientState != previousState)
{
//如果当前状态更新,则添加到字典
photonState.Add(previousState.ToString());
//更新previous
previousState = PhotonNetwork.NetworkClientState;
}
}
void OnGUI()
{
GUI.skin = skin;
//显示过程中的全部信息
/* for (int i = 0; i < photonState.Count; i++)
{
GUILayout.Label(photonState[i]);
}*/
//显示最新的
switch (PhotonNetwork.NetworkClientState)
{
//未连接状态
case ClientState.PeerCreated:
ConnectToPhotonCloud();
break;
case ClientState.ConnectedToMasterServer:
RoomOperation();
break;
}
GUILayout.Label(photonState[photonState.Count - 1]);
}
/// <summary>
/// 链接Photon Cloud
/// </summary>
private void ConnectToPhotonCloud()
{
if (GUILayout.Button("连接"))
{
//链接Photon Cloud
bool connectResult = PhotonNetwork.ConnectUsingSettings();
}
}
/// <summary>
/// 房间操作
/// </summary>
private void RoomOperation()
{
GUILayout.Label("情输入房间名称:");
roomName = GUILayout.TextField(roomName);
GUILayout.Label("情输入房间最大人数:");
roomMaxCount = GUILayout.TextField(roomMaxCount);
if (GUILayout.Button("创建房间"))
{
//房间设置
RoomOptions options = new RoomOptions();
options.MaxPlayers = byte.Parse(roomMaxCount);
//创建房间
PhotonNetwork.CreateRoom(roomName);
}
if (GUILayout.Button("进入游戏大厅"))
{
//进入游戏大厅
PhotonNetwork.JoinLobby();
}
if (GUILayout.Button("加入随机房间"))
{
//加入随机房间
PhotonNetwork.JoinRandomRoom();
}
}
}
连接成功后。
创建成功后。
4.0 回调
回调用于检测前序操作是否成功。
PhotonCallBackDemo :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PhotonCallBackDemo : MonoBehaviourPunCallbacks
{
public override void OnConnected()
{
base.OnConnected();
Debug.Log("Connected");
}
public override void OnConnectedToMaster()
{
base.OnConnectedToMaster();
Debug.Log("Connected To MasterServer");
}
public override void OnDisconnected(DisconnectCause cause)
{
base.OnDisconnected(cause);
Debug.Log("Disconnected:" + cause);
}
public override void OnCreatedRoom()
{
base.OnCreatedRoom();
Debug.Log("Create Room Success!!");
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
base.OnJoinRandomFailed(returnCode, message);
Debug.Log("Failed Join Random Room!!" + returnCode + " | " + message);
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
Debug.Log("joined Room!!");
}
public override void OnJoinedLobby()
{
base.OnJoinedLobby();
Debug.Log("Joined Lobby!!");
}
}
5.0 完善switch
photonDemo:
void OnGUI()
{
GUI.skin = skin;
//显示过程中的全部信息
/* for (int i = 0; i < photonState.Count; i++)
{
GUILayout.Label(photonState[i]);
}*/
//显示最新的
GUILayout.Label(photonState[photonState.Count - 1]);
switch (PhotonNetwork.NetworkClientState)
{
case ClientState.Joined:
JoinedRoomOperation();
break;
case ClientState.JoinedLobby:
JoinedLobbyOperation();
break;
}
if (GUILayout.Button("断开连接"))
{
PhotonNetwork.Disconnect();
}
}
private void JoinedLobbyOperation()
{
//PhotonNetwork.
}
private void JoinedRoomOperation()
{
}
6.0 加入房间
6.1 代码:
回调函数添加如下: PhotonCallBack:
public List<RoomInfo> roomList;
///
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
base.OnRoomListUpdate(roomList);
this.roomList = roomList;
}
photonDemo:
private PhotonCallBackDemo cbDemo;
///
private void JoinedLobbyOperation()
{
GUILayout.Label("Room List:");
GUILayout.Label("————————————————————");
foreach (var item in cbDemo.roomList)
{
if (!item.IsOpen || !item.IsVisible)
{
continue;
}
GUILayout.Label("房间名称:" + item.Name);
GUILayout.Label("房间信息:" + item.PlayerCount + "/" +item.MaxPlayers);
if(GUILayout.Button("加入房间"))
{
PhotonNetwork.JoinRoom(item.Name);
}
GUILayout.Label("--------------------");
}
GUILayout.Label("————————————————————");
}
6.2 测试:
多开几个测试
离开大厅
if (GUILayout.Button("离开大厅"))
{
PhotonNetwork.LeaveLobby();
}
完整代码:
photonDemo:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using System;
public class PhotonDemo : MonoBehaviour
{
public GUISkin skin;
#region GUI Fields
private List<string> photonState;
#endregion
/// <summary>
/// 标记上一次的状态
/// </summary>
private ClientState previousState;
private PhotonCallBackDemo cbDemo;
private string roomName = "room007";
private string roomMaxCount = "2";
private void Awake()
{
photonState = new List<string>();
cbDemo = GetComponent<PhotonCallBackDemo>();
}
private void Start()
{
//初始状态
previousState = PhotonNetwork.NetworkClientState;
photonState.Add(previousState.ToString());
}
private void Update()
{
if (PhotonNetwork.NetworkClientState != previousState)
{
//如果当前状态更新,则添加到字典
photonState.Add(previousState.ToString());
//更新previous
previousState = PhotonNetwork.NetworkClientState;
}
}
void OnGUI()
{
GUI.skin = skin;
//显示过程中的全部信息
/* for (int i = 0; i < photonState.Count; i++)
{
GUILayout.Label(photonState[i]);
}*/
//显示最新的
GUILayout.Label(photonState[photonState.Count - 1]);
switch (PhotonNetwork.NetworkClientState)
{
//未连接状态
case ClientState.PeerCreated:
ConnectToPhotonCloud();
break;
case ClientState.Disconnected :
ConnectToPhotonCloud();
break;
case ClientState.ConnectedToMasterServer:
RoomOperation();
break;
case ClientState.Joined:
JoinedRoomOperation();
break;
case ClientState.JoinedLobby:
JoinedLobbyOperation();
break;
}
if (GUILayout.Button("断开连接"))
{
PhotonNetwork.Disconnect();
}
}
private void JoinedLobbyOperation()
{
GUILayout.Label("Room List:");
GUILayout.Label("————————————————————");
foreach (var item in cbDemo.roomList)
{
if (!item.IsOpen || !item.IsVisible)
{
continue;
}
if (item.MaxPlayers == 0)
{
continue;
}
GUILayout.Label("房间名称:" + item.Name);
GUILayout.Label("房间信息:" + item.PlayerCount + "/" +item.MaxPlayers);
if(GUILayout.Button("加入房间"))
{
PhotonNetwork.JoinRoom(item.Name);
}
}
GUILayout.Label("————————————————————");
if (GUILayout.Button("离开大厅"))
{
PhotonNetwork.LeaveLobby();
}
}
private void JoinedRoomOperation()
{
}
/// <summary>
/// 链接Photon Cloud
/// </summary>
private void ConnectToPhotonCloud()
{
if (GUILayout.Button("连接"))
{
//链接Photon Cloud
bool connectResult = PhotonNetwork.ConnectUsingSettings();
}
}
/// <summary>
/// 房间操作
/// </summary>
private void RoomOperation()
{
GUILayout.Label("情输入房间名称:");
roomName = GUILayout.TextField(roomName);
GUILayout.Label("情输入房间最大人数:");
roomMaxCount = GUILayout.TextField(roomMaxCount);
if (GUILayout.Button("创建房间"))
{
//房间设置
RoomOptions options = new RoomOptions();
options.MaxPlayers = byte.Parse(roomMaxCount);
//创建房间
PhotonNetwork.CreateRoom(roomName,options);
}
if (GUILayout.Button("进入游戏大厅"))
{
//进入游戏大厅
PhotonNetwork.JoinLobby();
}
if (GUILayout.Button("加入随机房间"))
{
//加入随机房间
PhotonNetwork.JoinRandomRoom();
}
}
}
Photon CallBackDemo:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PhotonCallBackDemo : MonoBehaviourPunCallbacks
{
public List<RoomInfo> roomList;
public override void OnConnected()
{
base.OnConnected();
Debug.Log("Connected");
}
public override void OnConnectedToMaster()
{
base.OnConnectedToMaster();
Debug.Log("Connected To MasterServer");
}
public override void OnDisconnected(DisconnectCause cause)
{
base.OnDisconnected(cause);
Debug.Log("Disconnected:" + cause);
}
public override void OnCreatedRoom()
{
base.OnCreatedRoom();
Debug.Log("Create Room Success!!");
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
base.OnJoinRandomFailed(returnCode, message);
Debug.Log("Failed Join Random Room!!" + returnCode + " | " + message);
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
Debug.Log("joined Room!!");
}
public override void OnJoinedLobby()
{
base.OnJoinedLobby();
Debug.Log("Joined Lobby!!");
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
base.OnRoomListUpdate(roomList);
this.roomList = roomList;
}
}
7.0 房间设置
加入房间后,显示房间里的玩家
item.Value.IsLocal 是否为自己
item.Value.NickName 名称
private void JoinedRoomOperation()
{
GUILayout.Label("Player List:");
GUILayout.Label("————————————————————");
//找到当前房间,在遍历所有玩家
foreach (var item in PhotonNetwork.CurrentRoom.Players)
{
//逐个显示玩家
GUILayout.Label(item.Key +" : "+ item.Value.NickName + (item.Value.IsLocal? "√":""));
}
/* //之家遍历玩家列表,已经排好序,优先使用
foreach (var item in PhotonNetwork.PlayerList)
{
//逐个显示玩家
GUILayout.Label(item.ActorNumber + " : "+ item.NickName + (item.IsLocal ? "√" : ""));
}*/
GUILayout.Label("————————————————————");
if (GUILayout.Button("离开房间"))
{
PhotonNetwork.LeaveRoom();
}
}
用字典的话,上面的顺序随机,不会排好序
8.0 #玩家准备#
重点,photon未封装。
//之家遍历玩家列表,已经排好序,优先使用
foreach (var item in PhotonNetwork.PlayerList)
{
//逐个显示玩家
GUILayout.Label(item.ActorNumber + " : " + item.NickName + (item.IsLocal ? "√" : ""));
object isReady = false;
item.CustomProperties.TryGetValue("Ready",out isReady);//获取玩家属性
if (isReady == null || !(bool)isReady)
{
if (item.IsLocal && GUILayout.Button("准备"))
{
ExitGames.Client.Photon.Hashtable readyHash = new ExitGames.Client.Photon.Hashtable();
readyHash.Add("Ready", true);
item.SetCustomProperties(readyHash);
}
else
{
GUILayout.Label("【未准备】");
}
}
else
{
GUILayout.Label("【已准备】");
if (item.IsLocal && GUILayout.Button("取消准备"))
{
ExitGames.Client.Photon.Hashtable readyHash = new ExitGames.Client.Photon.Hashtable();
readyHash.Add("Ready", false);
item.SetCustomProperties(readyHash);
}
}
//PhotonNetwork.CurrentRoom.CustomProperties
}
9.0 异端实例化
新建工程,为FPS游戏。
创建UI界面布局如下:
新建代码Launcher.cs,挂载到Canvans组件上, 给按键绑定事件,可以开始测试玩家实例化。
using System.Coallections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.UI;
using Photon.Realtime;
public class Launcher : MonoBehaviourPunCallbacks
{
public InputField RoomName;
public string PlayerPrefabName;
private bool connectToMaster;
private bool joinRoom;
public void ConnectToMaster()
{
PhotonNetwork.ConnectUsingSettings();//链接Photon Cloud
PhotonNetwork.GameVersion = "Alpha";
}
public void CreatRoom()
{
if (!connectToMaster || joinRoom) return;
PhotonNetwork.CreateRoom(RoomName.text,
new RoomOptions() { MaxPlayers = 16 },
TypedLobby.Default);
}
public void JoinRoom()
{
if (!connectToMaster || joinRoom) return;
PhotonNetwork.JoinRoom(RoomName.text);
}
public override void OnConnectedToMaster()//回调
{
base.OnConnectedToMaster();
connectToMaster = true;
}
public override void OnCreatedRoom()//回调
{
base.OnCreatedRoom();
joinRoom = true;
}
public override void OnJoinedRoom()//回调
{
base.OnJoinedRoom();
Debug.Log("Joined Room");
PhotonNetwork.Instantiate(PlayerPrefabName, Vector3.zero, Quaternion.identity);//通过string名字实例化
}
}
玩家实例化使用脚本:PhotonNetwork.Instantiate(PlayerPrefabName, Vector3.zero, Quaternion.identity);
在使用前需要在prefab下挂载Photon View组件,且prefab放在Resources目录下。
打包后开启工程,运行两个后,可以看见两个玩家加载进来。
10.0 玩家同步
为prefab添加组件两个
动画同步文章来源:https://www.toymoban.com/news/detail-482205.html
文章来源地址https://www.toymoban.com/news/detail-482205.html
到了这里,关于Unity_Photon的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!