首页 > 其他分享 >Unity_Photon

Unity_Photon

时间:2023-05-30 22:12:02浏览次数:68  
标签:void Photon GUILayout private Label item Unity PhotonNetwork

Photon

Photon搭建

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

链接成功。

创建房间

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

房间创建连接成功后。

join创建成功后。

回调

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

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

测试:

多开几个测试

房间01

房间02

房间03

离开大厅

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

房间设置

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

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
        }

房间准备

标签:void,Photon,GUILayout,private,Label,item,Unity,PhotonNetwork
From: https://www.cnblogs.com/Leslielei/p/17437347.html

相关文章

  • Unity中根据平面的多边形点的数据,生成简单的立体网格
    todo 最近需要一个功能,就是根据给定的多边形顶点(按照顺时针或者逆时针这样的顺序),然后生成一个具有高度,投影与多边形一样的一个Mesh。效果如下,比如给定以下的一些顶点的位置         https://blog.csdn.net/lxbhahaha/article/details/111687476......
  • Unity发布IOS发布Android版本出现屏幕问题 UGUI半屏被压缩 另一半黑屏
    项目场景:用Unity做的app发布的ios和Android版本,ui做屏幕自适应,来适配多机型,unity版本是2019.4,用的UGUI。问题描述:极个别机型有个偶发的问题,就是在app息屏,再开屏的时候,会出现半边屏幕被压缩,半边屏幕黑屏的问题,但是ui交互的位置还是正常的,bug效果图如下:跟这张图一样的<hrstyle="bor......
  • Unity3d安装教程
    一、下载UnityHubUnityhub是一个Unity项目管理工具,可以装多个版本的unity编辑器Unity实时内容开发平台-实时3D引擎、2D、VR&AR可视化数据|Unity中国官网点击下载此时需要登录才可以下载这里我们可以使用我们熟悉的微信登录登录好以后,这里会有微信头像,再次点击下载......
  • Unity 对多边形进行矩形分割和查找最大内接矩形
     花了点时间实现了对任意多边形进行矩形分割的功能,有需要的小伙伴可以点这里查看源码 一、实现效果:1、对图片里的内容进行矩形分割     2、对多边形顶点数据进行矩形分割    3、查找图片里内容的最大内接矩形    4、查找多边形顶点数据内的最大内......
  • Unity,发布ios和Android的包,UGUI,异形屏适配问题。
    Unity,发布ios和Android的包,UGUI,异形屏适配问题。@TOC<hrstyle="border:solid;width:100px;height:1px;"color=#000000size=1">前言unity发布移动端需要做ui的适配,我们用的是UGUI,暂且提供一种我们自己的ui适配解决方案,包含异形屏的。<hrstyle="border:solid;width:100px;h......
  • Unity的AssetPostprocessor之Model:深入解析与实用案例 1
    UnityAssetPostprocessor模型相关函数详解在Unity中,AssetPostprocessor是一个非常有用的工具,它可以在导入资源时自动执行一些操作。在本文中,我们将重点介绍AssetPostprocessor中与模型相关的函数,并提供多个使用例子。OnPostprocessModelOnPostprocessModel是AssetPostprocessor......
  • Unity的Undo:详解解析与实用案例
    UnityUndo详解在Unity中,Undo是一个非常重要的功能,它可以让开发者在编辑器中进行操作时,随时撤销之前的操作,从而避免不必要的错误。本文将详细介绍UnityUndo实现原理和使用方法,并提供多个使用例子,帮助开发者更好地理解和应用该功能。实现原理UnityUndo的实现原理是通过记录每个......
  • Unity的Console的控制类LogEntries:深入解析与实用案例
    使用UnityConsole窗口的LogEntries私有类实现自定义日志系统在Unity开发过程中,我们经常需要使用Console窗口来查看程序运行时的日志信息。Unity内置的日志系统提供了基本的日志功能,但有时我们需要更多的自定义选项。本文将介绍如何使用UnityConsole窗口的LogEntries私有类来实现......
  • Unity的Undo:详解解析与实用案例
    UnityUndo详解在Unity中,Undo是一个非常重要的功能,它可以让开发者在编辑器中进行操作时,随时撤销之前的操作,从而避免不必要的错误。本文将详细介绍UnityUndo实现原理和使用方法,并提供多个使用例子,帮助开发者更好地理解和应用该功能。实现原理UnityUndo的实现原理是通过记录每个......
  • unity学习日志5(麦扣老师3DRPG项目学习)
    设计模式单例模式(泛型单例)作用:提高代码复用率,增加代码可读性//实现泛型单例,并对T进行约束,规定只有各类manager使用单例模式publicclassSingleton<T>:MonoBehaviourwhereT:Singleton<T>{privatestaticTinstance;//通过属性来访问直接获取私有的静......