Unity问题与解决方案:Photon同步数据的四种方式

2023-10-25 17:48

本文主要是介绍Unity问题与解决方案:Photon同步数据的四种方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

从我目前get到的点钟,大概是有三个方法,第一个方法是使用PhotonNetwork.RPC方法,该方法接收方法名,发送对象(PhotonPlayer或PhotonTarget)和方法参数,并调用声明[PUNRPC]的相关方法,但根据源码:

//<summary>
/// Internal to send an RPC on given PhotonView. Do not call this directly but use: PhotonView.RPC!
/// </summary>
internal static void RPC(PhotonView view, string methodName, PhotonTargets target, bool encrypt, params object[] parameters)

很明显该方法并不被推荐适用(Do not call this directly but use: PhotonView.RPC!

第二个方法则是按照PhotonView同步的方式,模仿PhotonTransformView等写一个自己的脚本,如果要仿照的话,PhotonRigidbodyView的实现较为简单,可以参考,来看一下原码:

using System;
using UnityEngine;
using Object = System.Object;/// <summary>
/// This class helps you to synchronize the velocities of a physics RigidBody.
/// Note that only the velocities are synchronized and because Unitys physics
/// engine is not deterministic (ie. the results aren't always the same on all
/// computers) - the actual positions of the objects may go out of sync. If you
/// want to have the position of this object the same on all clients, you should
/// also add a PhotonTransformView to synchronize the position.
/// Simply add the component to your GameObject and make sure that
/// the PhotonRigidbodyView is added to the list of observed components
/// </summary>
[RequireComponent(typeof(PhotonView))]
[RequireComponent(typeof(Rigidbody))]
[AddComponentMenu("Photon Networking/Photon Rigidbody View")]
public class PhotonRigidbodyView : MonoBehaviour, IPunObservable
{[SerializeField]bool m_SynchronizeVelocity = true;[SerializeField]bool m_SynchronizeAngularVelocity = true;Rigidbody m_Body;void Awake(){this.m_Body = GetComponent<Rigidbody>();}public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info){if (stream.isWriting == true){if (this.m_SynchronizeVelocity == true){stream.SendNext(this.m_Body.velocity);}if (this.m_SynchronizeAngularVelocity == true){stream.SendNext(this.m_Body.angularVelocity);}}else{if (this.m_SynchronizeVelocity == true){this.m_Body.velocity = (Vector3)stream.ReceiveNext();}if (this.m_SynchronizeAngularVelocity == true){this.m_Body.angularVelocity = (Vector3)stream.ReceiveNext();}}}
}

从中不难看到,实现的关键是实现IPunObservable接口和接口对应的方法,该实现通过判断stream的读写状态来执行SendNextReceiveNext,要注意发送和接收的数据流和接收逻辑必须是一一对应的,否则会出现值无法对应的情况。

另外一个特别需要注意的问题!如果是基础数据类型,是可以直接SendNext和ReceiveNext的,但是如果是自定义类型,需要在Photon中进行注册,相关文档在PhotonUnity的Document中有,可以去看一下链接,这里列出序列化的代码实例:

如对于我自定义的一个增益属性类Plugin

public class Camp
{public int camp;
}

有两种注册方式(其实差别不大,只是其中一个使用了Photon提供给我们的流)来进行注册,这里只展示第一种

即扩展该类,添加序列化和反序列化的静态方法:

public class Camp
{public int camp;public static byte[] SerializableClass(object plugin)//参数必须是object{Campp = (Camp) plugin;int intlen = Marshal.SizeOf(typeof(int));/** 创建字节序列*/byte[] bytes = new byte[intlen];/** 序列化*/int index = 0;Protocol.Serialize(p.camp, bytes, ref index);return bytes;}public static object DeserializeClass(byte[] bytes){Plugin plugin = new Plugin();int index = 0;Protocol.Deserialize(out plugin.camp, bytes, ref index);return plugin;}
}

随后在任意位置注册一次即可:

PhotonPeer.RegisterType(typeof(Plugin), (byte) 'a',SerializableClass,DeserializeClass);

注意关于第二个是类似占位符的形式,已经注册过的byte不能再次注册,以及被官方注册过的字节有:W/V/Q/P这四种,分别代表Vector3,Vector2,QuaternionPhotonPlayer

然后关于一些其他的字节之间相互转化的方法可以参考一下极客学院的关于Photon的一个公开课,链接,这里就不详细展开了


然后我基于build模式和最近rx系列的思路写了一个传输类,能简化一下stream传输的逻辑,也附在这吧


public class PhotonTranser
{private PhotonStream stream;public static PhotonTranser create(PhotonStream stream){return new PhotonTranser(stream);}private PhotonTranser(PhotonStream stream){this.stream = stream;}public PhotonTranser sendnext(object value,bool realSend){if (realSend &&stream.isWriting) {stream.SendNext(value);}return this;}public PhotonTranser sendnext(object value){if (stream.isWriting){stream.SendNext(value); }return this;}public PhotonTranser receive(Func<object, object> value,bool realRecv){if (realRecv &&!stream.isWriting){value(stream.ReceiveNext());}return this;}public PhotonTranser receive(Func<object, object> value){if (!stream.isWriting){value(stream.ReceiveNext());    }return this;}public void finish(){}}

按照该类的实现,PhotonRigidbodyView中的OnPhotonSerializeView实现就可以改为:

PhotonTranser.create(stream).sendnext(this.m_Body.velocity, this.m_SynchronizeVelocity).sendnext(this.m_Body.angularVelocity,this.m_SynchronizeAngularVelocity).receive(new Func<object, object>(delegate(object o){this.m_Body.velocity = (Vector3) o;return null;}), this.m_SynchronizeVelocity).receive(new Func<object, object>(delegate(object o){this.m_Body.angularVelocity = (Vector3) o;return null;}),this.m_SynchronizeAngularVelocity  ).finish();

感觉这样下来会就比较直观,不过由于C#半路出家..一些语法不是很了解,不清楚有没有更简单的实现方式,比如lambda等(猜的),有人有思路可以提供一下

第三种方法有条件,就是只能在用PhotonNetwork.Instantiate实例化对象的时候传递,具体的方式可以参考一下我的这一篇博客:

Photon实例化(PhotonNetwork.Instantiate参数详解)

这篇关于Unity问题与解决方案:Photon同步数据的四种方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/284190

相关文章

Django中的函数视图和类视图以及路由的定义方式

《Django中的函数视图和类视图以及路由的定义方式》Django视图分函数视图和类视图,前者用函数处理请求,后者继承View类定义方法,路由使用path()、re_path()或url(),通过in... 目录函数视图类视图路由总路由函数视图的路由类视图定义路由总结Django允许接收的请求方法http

使用Python开发一个Ditto剪贴板数据导出工具

《使用Python开发一个Ditto剪贴板数据导出工具》在日常工作中,我们经常需要处理大量的剪贴板数据,下面将介绍如何使用Python的wxPython库开发一个图形化工具,实现从Ditto数据库中读... 目录前言运行结果项目需求分析技术选型核心功能实现1. Ditto数据库结构分析2. 数据库自动定位3

Python yield与yield from的简单使用方式

《Pythonyield与yieldfrom的简单使用方式》生成器通过yield定义,可在处理I/O时暂停执行并返回部分结果,待其他任务完成后继续,yieldfrom用于将一个生成器的值传递给另一... 目录python yield与yield from的使用代码结构总结Python yield与yield

pandas数据的合并concat()和merge()方式

《pandas数据的合并concat()和merge()方式》Pandas中concat沿轴合并数据框(行或列),merge基于键连接(内/外/左/右),concat用于纵向或横向拼接,merge用于... 目录concat() 轴向连接合并(1) join='outer',axis=0(2)join='o

Linux线程同步/互斥过程详解

《Linux线程同步/互斥过程详解》文章讲解多线程并发访问导致竞态条件,需通过互斥锁、原子操作和条件变量实现线程安全与同步,分析死锁条件及避免方法,并介绍RAII封装技术提升资源管理效率... 目录01. 资源共享问题1.1 多线程并发访问1.2 临界区与临界资源1.3 锁的引入02. 多线程案例2.1 为

shell脚本批量导出redis key-value方式

《shell脚本批量导出rediskey-value方式》为避免keys全量扫描导致Redis卡顿,可先通过dump.rdb备份文件在本地恢复,再使用scan命令渐进导出key-value,通过CN... 目录1 背景2 详细步骤2.1 本地docker启动Redis2.2 shell批量导出脚本3 附录总

批量导入txt数据到的redis过程

《批量导入txt数据到的redis过程》用户通过将Redis命令逐行写入txt文件,利用管道模式运行客户端,成功执行批量删除以Product*匹配的Key操作,提高了数据清理效率... 目录批量导入txt数据到Redisjs把redis命令按一条 一行写到txt中管道命令运行redis客户端成功了批量删除k

Oracle查询表结构建表语句索引等方式

《Oracle查询表结构建表语句索引等方式》使用USER_TAB_COLUMNS查询表结构可避免系统隐藏字段(如LISTUSER的CLOB与VARCHAR2同名字段),这些字段可能为dbms_lob.... 目录oracle查询表结构建表语句索引1.用“USER_TAB_COLUMNS”查询表结构2.用“a

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Oracle数据库定时备份脚本方式(Linux)

《Oracle数据库定时备份脚本方式(Linux)》文章介绍Oracle数据库自动备份方案,包含主机备份传输与备机解压导入流程,强调需提前全量删除原库数据避免报错,并需配置无密传输、定时任务及验证脚本... 目录说明主机脚本备机上自动导库脚本整个自动备份oracle数据库的过程(建议全程用root用户)总结