PhotonPhoton搭建

(2条消息) 【Unity3D】Photon环境搭建_photon框架_little_fat_sheep的博客-CSDN博客

连接云服务器

主要代码 :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 photonState;    #endregion    ///     /// 标记上一次的状态    ///     private ClientState previousState;    private void Awake()    {        photonState = new List();    }    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]);        }            }}

链接成功。

创建房间

状态: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 photonState;    #endregion    ///     /// 标记上一次的状态    ///     private ClientState previousState;    private string roomName = "room007";    private string roomMaxCount = "2";    private void Awake()    {        photonState = new List();    }    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]);    }    ///     /// 链接Photon Cloud    ///     private void ConnectToPhotonCloud()    {        if (GUILayout.Button("连接"))        {            //链接Photon Cloud            bool connectResult = PhotonNetwork.ConnectUsingSettings();        }    }    ///     /// 房间操作    ///     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();        }    }}

连接成功后。

创建成功后。

回调

回调用于检测前序操作是否成功。

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!!");    }}

完善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()    {    }

加入房间代码:

回调函数添加如下: PhotonCallBack:

    public List roomList;    ///        public override void OnRoomListUpdate(List 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("————————————————————");    }

测试:

多开几个测试

离开大厅

        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 photonState;    #endregion    ///     /// 标记上一次的状态    ///     private ClientState previousState;    private PhotonCallBackDemo cbDemo;    private string roomName = "room007";    private string roomMaxCount = "2";    private void Awake()    {        photonState = new List();        cbDemo = GetComponent();    }    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()    {    }    ///     /// 链接Photon Cloud    ///     private void ConnectToPhotonCloud()    {        if (GUILayout.Button("连接"))        {            //链接Photon Cloud            bool connectResult = PhotonNetwork.ConnectUsingSettings();        }    }    ///     /// 房间操作    ///     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 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 roomList)    {        base.OnRoomListUpdate(roomList);        this.roomList = roomList;    }}

房间设置

加入房间后,显示房间里的玩家

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();        }    }

用字典的话,上面的顺序随机,不会排好序

#玩家准备#

重点,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        }