unity3d和虚幻4哪个好一直操作超时怎么办

Unity 3D Photon服务器 - 简书
Unity 3D Photon服务器
周末两天又捡起了以前粗略接触过的Photon服务器,当时只是学会了怎么用PUN插件现学现卖一个远程共享操作,对原理什么的都不求甚解。这次又重新从头开始打算用Photon实现Chatroom和一个多人MMO Demo。下面是学习后用XMind做的一个总结图。
Photon.png
Photon简介
Photon是Exit Games公司推出的服务端网络游戏引擎,也是一款实时的Socket服务器和开发框架。Photon使用起来非常方便,也容易扩展。Photon包含两个部分,一部分是一个socket服务器,另一部分是其针对各个平台编写的SDK。服务端架构在windows系统平台上,采用C#语言编写。客户端SDK提供了多种平台的开发API,其中就包括Unity 3D客户端。Photon服务器底层内核采用C++编写,上层用C#进行了一层封装,为开发者提供接口进行业务逻辑的编写,提高了服务器框架的开发效率。
Photon引擎的特点如下:1. 架构于Windows平台下原生态性能高度优化的系统。2. 经过实践证明适用于众多的商业游戏,常在手机网游服务器框架中使用。典型案例包括Glu公司的Indestructible、Eternity Warriors 3和Innogames公司的Kartuga等游戏的服务器。3. 服务器端游戏逻辑采用C#语言实现。4. 采用纤程处理消息机制以避免采用线程导致的问题(资源竞争、占用冲突、多线程通讯)。5. 部署简单,支持云端服务(Photon Cloud)。6. 采用小尺寸的二进制协议,可根据需要使用有序可靠的UDP协议。UDP协议不需要验证数据传输的准确性。Photon也支持TCP、UDP、Websocket。7. 封装了跨平台(Unity 3D、Cocos2d-x、Android、iOS、Html5、Flash)的网络层模块。
配置Photon服务器
安装Photon SDK
前往下载v3.1版本的SDK。下载完毕后解压可得到deploy、doc、lib和src-server共4个文件目录。deploy是各个平台下的photon服务器可执行文件。doc是帮助文件。lib是已经编译好的dll文件,部署服务器时使用。src-server里面是游戏demo源码。
运行PhotonControl.exe文件
运行PhotonControl.exe,在工具栏中找到photon服务器的图标,右键选择Default-&Start as application(不同版本Photon可能不一样,有的是Default)运行Photon服务器。成功后photon服务器图标是蓝色的,否则就是运行异常。
设置Photon配置文件
我们可以通过deploy中不同平台目录下的PhotonServer.config配置文件来修改Photon服务器的配置。在配置文件中,default节点里可以设置传输的最大消息尺寸、最大/最小超时时限。在UDPListener和TCPListener节点中可以设置监听UDP和TCP连接的ip地址和通信端口。在Websocket节点中可以进行Websocket通信的一些设置。Application节点比较重要,每个Application的name在通讯接口方法调用时要用到。
检查Windows系统里的端口和防火墙设置
启动Default-&Run TestClient ,运行客户端测试程序,如果在运行过程中弹出Windows防火墙提示,就需要在Windows防火墙里开放了Photon配置文件中设定的协议端口。如果没有弹出提示,必要时需要在Windows防火墙高级设置中手动创建入站规则。因为在这种情况下有可能防火墙是针对Photon服务器程序创建的入站规则,不限制使用端口。而我们可以手动创建针对UDP和TCP通信的特定端口的入站规则。
Photon异常排查
当我们启动PhotonControl.exe后,点击图标中的Default-&Start as application,运行一段时间服务器停止,图标变为灰色,说明Photon服务器运行异常。我们需要先检查一下Photon服务器的端口设置。如果排除了端口和防火墙设置的影响,我们可以通过日志文件Photon-Default查看是否是启动Photon服务器过程中发生了异常。如果排除了Photon服务器启动异常,就需要打开各个游戏服务端程序的日志文件查看是哪个游戏服务器程序异常。
Photon客户端开发
Unity 3D连接Photon服务器
导入Photon3Unity3D.dll到U3D工程的Assets/Plugins目录下。编写客户端脚本文件与Photon服务器通信,继承IPhotonPeerListener接口并实现OnStatusChanged接口方法。在Update方法中调用PhotonPeer对象的Service方法就可以与Photon服务器通信了。只有调用Service方法,我们才能正常与服务器进行连接和通信。
向Photon服务器发送请求
首先需要编写一个SendMessage函数,从客户端向服务器发送请求,使用PhotonPeer对象的OpCustom方法来发送请求。同时需要实现OnOperationResponse和OnEvent接口方法来处理服务器返回的结果。
处理Photon服务器返回的响应
实现OnOperationResponse函数
可以通过OperationCode分析服务器返回响应的类型。
编写函数处理Photon服务器返回的消息
自定义事件
实现OnEvent函数
设定游戏操作枚举
传输自定义数据参数
Photon服务器和Unity 3D客户端的通信机制
发送请求到Photon服务器
处理Photon服务器返回的响应
完成游戏房间的操作
实现自定义事件
Photon 服务端编写
在编写自己的Photon服务器的时候,需要使用到Photon SDk提供的ExitGamesLibs.dll、Photon.SocketServer.dll、PhotonHostRuntimeInterfaces.dll这三个dll文件。复制dll到自己创建的类库项目,并在C#工程中添加引用。确认添加的引用的“复制本地”属性为True,如果不为True,将“嵌入互操作类型”由True改为False。在Photon服务器目录的deploy目录下创建自己相关项目的服务器目录,修改类库项目的输出路径为这个目录。还需要修改PhotonServer.config文件,添加自定义服务器的Application节点。实现ApplicationBase接口(解析引入Photon.SocketServer、实现抽象类自动导入抽象方法)
创建Application类
创建一个Photon游戏服务器项目
创建Application类
实现LiteApplication接口:需要引入Lite.dll文件。实现CreatePeer接口
创建Peer类
Peer类负责创建和每个客户端的会话并处理每一个客户端的请求。
接收和处理客户端的请求
自定义枚举,实现OnOperationResponse函数
除了LitePeer父类里定义的基于房间的操作类型,还可以自定义操作类型。
广播自定义事件
Photon通信协议
Photon传输数据类型的限制
在Photon的官方文档中给出了Photon通讯协议支持的数据类型,Photon只能传输基本的数据类型,并不支持传输自定义的对象类型,但是可以通过序列化和反序列化的方式来实现对象传输。客户端和服务端要保持相同的序列化和反序列化方法,服务端要注册自定义对象。
序列化和反序列化方法
面对多类型多成员的对象的序列化工作,可以使用第三方的序列化工具,就可以不必对每一类对象都编写一套序列化和反序列化方法。可以采用的第三方组件包括NewtonSoft.Json.dll和protobuf-net.dll。两者的区别是:NewtonSoft是将自定义类型转化为JSON字符串,Protobuf将自定义类型直接转化为byte数组。对于同样大小的自定义类型来说,protobuf转化后数据量更小,传输效率也更高,因此也更加常用。
Protobuf插件
Protobuf的优点:1)性能好,效率高 2)代码生成机制,数据解析类自动生成 3)支持向后兼容和向前兼容。4)支持java、C++、C#等多种编程语言。
在Photon服务端使用Protobuf
在Unity 3D客户端使用Protobuf
Photon MMO
PhotonView
当场景中的任何一个组件被加上PhotonView时,会动态地在多个客户端之间同步组件的数据和状态。
多场景公用Photon对象
在多个场景如果都通过实例化Peer对象,并建立与Photon服务器的连接,及其消耗资源,可以采用共享静态Photon连接对象的方式,或者把连接功能提取出来做成一个组件,采用DontDestroy方法在加载时保留原有连接,类似连接池的思想。
PUN VS. Photon服务器原生插件
PUN是更接近Unity Networking组件的一种对Photon原生功能的封装。如果对于UN熟悉,可以使用PUN插件,如果没接触UN,直接使用Photon服务器原生插件进行开发。
还在整理和补充中...
0岁产品经理
Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线)。分布式系统的协调导致了样板模式, 使用Spring Cloud开发人员可以快速地支持实现这些模式的服务和应用程序。他们将在任何分布式...
发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注
09:45字数 61697阅读 3316评论 2喜欢 85 用到的组件 1、通过CocoaPods安装 项目名称 项目信息 AFNetworking 网络请求组件 FM...
用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金Cover 有什么料? 从这篇文章中你能获得这些料: 知道setContentView()之后发生了什么? ... Android 获取 View 宽高的常用正确方式,避免为零 - 掘金相信有很多朋友...
一、温故而知新 1. 内存不够怎么办 内存简单分配策略的问题地址空间不隔离内存使用效率低程序运行的地址不确定 关于隔离 : 分为 虚拟地址空间 和 物理地址空间 分段 : 把一段程序所需要的内存空间大小映射到某个地址空间 分页 : 把地址空间人为地等分成固定大小的页,每一页...
百战程序员_ Java1573题 QQ群:034603 掌握80%年薪20万掌握50%年薪10万 全程项目穿插, 从易到难,含17个项目视频和资料持续更新,请关注www.itbaizhan.com 国内最牛七星级团队马士兵、高淇等11位十年开发经验专...
解压缩模块zlib
最近很流行的一段话“如果我用你待我的方式来待你,恐怕你早已离去”好好体会这句话,适合任何关系。
我记得大话西游里至尊宝对紫霞仙子说“曾经有一份真挚的感情放在我面前,可是我没有珍惜,等到失去的时候才后悔莫及,如果上天给我再来一次的机会,我会对那个女孩子说三个字,我爱你...
(文/李远红) 月亮爬上了山坡 冷冷清清 夜已深沉 谁在寂寞地吹箫 不忍心打断 若不是你的来到 空气里怎么会飘香 月亮也对空梳妆 你眼睛里的光亮 饱含着伤 梦中的絮絮叨叨 是多么荒诞 经不起打量
今天要给大家讲的是一位80后的父亲,他2009年毕业于山东省某所大学,三年大学时光基本是在网吧和宿舍中度过的,可谓是白白浪费了三年的大好时光和三年父母的辛苦血汗钱(你说可气不?父母辛苦出力赚点钱就为了让孩子上大学多学点知识,以后好有出息,你说这败家玩意根本不体谅做父母的苦衷...
带着两个小男孩,奔着刘德华去看《追龙》,看了以后才发现原来第一主角是甄子丹,本以为的励志篇却变成暴力的江湖片。 《追龙》好励志的一个电影名,没想到在电影里的意思是吸毒,是黑社会的行话。 电影的故事背景发生在1974年以前的香港,那时候的香港是英国的殖民地,是香港最黑暗的年代...感谢评语:
本页链接:
网友们正在为您出谋划策,请耐心等待!
最新解决问题列表
猜你感兴趣游戏蛮牛学习群(纯技术交流,不闲聊):
扫一扫,访问微社区
后使用快捷导航没有帐号?
签到成功!您今天第{todayrank}个签到,签到排名竞争激烈,记得每天都来签到哦!已连续签到:{constant}天,累计签到:{days}天
关注:2258
当前位置: &
__________________________________________________________________________________
开发者干货区版块规则:
  1、文章必须是图文形式。(至少2幅图)
& && &2、文章字数必须保持在1500字节以上。(编辑器右下角有字数检查)
& && &3、本版块只支持在游戏蛮牛原创首发,不支持转载。
& && &4、本版块回复不得无意义,如:顶、呵呵、不错......【真的会扣分的哦】
& && &5、......
__________________________________________________________________________________
查看: 508|回复: 16
用Unity做一个壁纸程序
9排名<font color="#FF昨日变化3主题帖子积分
蛮牛币3809
在线时间1139 小时
发表于 昨天&10:13
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
才可以下载或查看,没有帐号?
效果如下图
TIM截图47.jpg (215.41 KB, 下载次数: 0)
昨天&10:08 上传
主要代码如下:
[C#] 纯文本查看 复制代码using S
using System.D
using System.Runtime.InteropS
using UnityE
using UnityEngine.UI;
public class WallPaper : MonoBehaviour
[DllImport(&user32.dll&)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport(&user32.dll&)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string className, string winName);
[DllImport(&user32.dll&)]
public static extern IntPtr SetParent(IntPtr hwnd, IntPtr parentHwnd);
[DllImport(&user32.dll&, CharSet = CharSet.Auto)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
[DllImport(&user32.dll&)]
public static extern bool EnumWindows(EnumWindowsProc proc, IntPtr lParam);
public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
[DllImport(&user32.dll&)]
public static extern IntPtr SendMessageTimeout(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam, uint fuFlage, uint timeout, IntPtr result);
public int ResW//窗口宽度
public int ResH//窗口高度
IntPtr wallP
void Main()
ResWidth = Screen.
ResHeight = Screen.
//Screen.SetResolution(ResWidth, ResHeight, true, 30);
if (Application.platform == RuntimePlatform.WindowsPlayer)
wallPaper = FindWindow(&WallPaper&, null);
IntPtr progman = FindWindow(&Progman&, null);
IntPtr result = IntPtr.Z
// 向 Program Manager 窗口发送 0x52c 的一个消息,超时设置为0x3e8(1秒)。
SendMessageTimeout(progman, 0x52c, IntPtr.Zero, IntPtr.Zero, 0, 0x3e8, result);
EnumWindows((hwnd, lParam) =&
// 找到包含 SHELLDLL_DefView 这个窗口句柄的 WorkerW
if (FindWindowEx(hwnd, IntPtr.Zero, &SHELLDLL_DefView&, null) != IntPtr.Zero)
// 找到当前 WorkerW 窗口的,后一个 WorkerW 窗口。
IntPtr tempHwnd = FindWindowEx(IntPtr.Zero, hwnd, &WorkerW&, null);
// 隐藏这个窗口
ShowWindow(tempHwnd, 0);
}, IntPtr.Zero);
SetParent(wallPaper, progman);
// Use this for initialization
void Start()
// Update is called once per frame
void Update()
private void OnApplicationFocus(bool focus)
t.text += & focus:& +
//ShowWindow(wallPaper, 0);
参考文章https://www.cnblogs.com/jiuxuan/p/7282541.html
目前的bug:程序初次运行会显示在最前方,切换其他程序后也会跳到最前方,Win+D之后就正常
项目地址https://gitee.com/awnuxcvbn/WallPaper.git
给力的!!
每日推荐:
4403/500排名<font color="#FF昨日变化48主题帖子积分
四处流浪, 积分 403, 距离下一级还需 97 积分
四处流浪, 积分 403, 距离下一级还需 97 积分
在线时间146 小时
发表于 昨天&11:02
楼主,看起来碉堡了
每日推荐:
12排名<font color="#FF昨日变化3主题帖子积分
蛮牛币3284
在线时间2771 小时
发表于 昨天&11:47
秀得一批!!
每日推荐:
4494/500排名<font color="#FF昨日变化67主题帖子积分
四处流浪, 积分 494, 距离下一级还需 6 积分
四处流浪, 积分 494, 距离下一级还需 6 积分
在线时间105 小时
发表于 昨天&14:00
我陈独秀会都不开了,就看你秀壁纸。
每日推荐:
5673/1000排名<font color="#FF昨日变化19主题帖子积分
熟悉之中, 积分 673, 距离下一级还需 327 积分
熟悉之中, 积分 673, 距离下一级还需 327 积分
蛮牛币1655
在线时间168 小时
发表于 昨天&14:38
这个很厉害,很接地气~
每日推荐:
61448/1500排名<font color="#FF昨日变化10主题帖子积分
蛮牛粉丝, 积分 1448, 距离下一级还需 52 积分
蛮牛粉丝, 积分 1448, 距离下一级还需 52 积分
蛮牛币2584
在线时间388 小时
发表于 昨天&14:54
谢谢楼主分享
每日推荐:
61075/1500排名<font color="#FF昨日变化7主题帖子积分
蛮牛粉丝, 积分 1075, 距离下一级还需 425 积分
蛮牛粉丝, 积分 1075, 距离下一级还需 425 积分
蛮牛币1585
在线时间323 小时
发表于 昨天&15:20
学习一下!!!
每日推荐:
5892/1000排名<font color="#FF昨日变化15主题帖子积分
熟悉之中, 积分 892, 距离下一级还需 108 积分
熟悉之中, 积分 892, 距离下一级还需 108 积分
在线时间222 小时
发表于 昨天&15:59
iopoipoioipoipioiop
每日推荐:
73049/5000排名<font color="#FF昨日变化9主题帖子积分
日久生情, 积分 3049, 距离下一级还需 1951 积分
日久生情, 积分 3049, 距离下一级还需 1951 积分
蛮牛币2487
在线时间437 小时
发表于 昨天&17:52
每日推荐:
71825/5000排名<font color="#FF昨日变化22主题帖子积分
日久生情, 积分 1825, 距离下一级还需 3175 积分
日久生情, 积分 1825, 距离下一级还需 3175 积分
蛮牛币3000
在线时间242 小时
发表于 昨天&18:20
每日推荐:
4305/500排名<font color="#FF昨日变化129主题帖子积分
四处流浪, 积分 305, 距离下一级还需 195 积分
四处流浪, 积分 305, 距离下一级还需 195 积分
在线时间44 小时
发表于 昨天&19:22
每日推荐:
61193/1500排名<font color="#FF昨日变化11主题帖子积分
蛮牛粉丝, 积分 1193, 距离下一级还需 307 积分
蛮牛粉丝, 积分 1193, 距离下一级还需 307 积分
蛮牛币2126
在线时间394 小时
发表于 8&小时前
看起来碉堡了,前排观看,
每日推荐:
61149/1500排名<font color="#FF昨日变化6主题帖子积分
蛮牛粉丝, 积分 1149, 距离下一级还需 351 积分
蛮牛粉丝, 积分 1149, 距离下一级还需 351 积分
蛮牛币1531
在线时间305 小时
发表于 8&小时前
谢谢分享!
每日推荐:
72868/5000排名<font color="#FF昨日变化主题帖子积分
日久生情, 积分 2868, 距离下一级还需 2132 积分
日久生情, 积分 2868, 距离下一级还需 2132 积分
蛮牛币4165
在线时间575 小时
发表于 7&小时前
嗯。。 有意思啊
每日推荐:
5518/1000排名<font color="#FF昨日变化3主题帖子积分
熟悉之中, 积分 518, 距离下一级还需 482 积分
熟悉之中, 积分 518, 距离下一级还需 482 积分
在线时间86 小时
发表于 6&小时前
每日推荐:
游戏蛮牛给予质量较高、影响力较大的unity相关技术开发者的荣誉称号
社区QQ达人
使用QQ帐号登录论坛的用户
累积数量不足1000蛮牛币
累积数量达到1000蛮牛币
连续签到30天很多人因为放不下一切,只好放弃梦想。
关于 Unity3D 网络请求的笔记
Unity 脚本 关于网络请求的方法有如下:
public WWW (string url, byte[] postData, Dictionary&string, string& headers)
public WWW (string url, byte[] postData, Hashtable headers)
deprecated
public WWW (string url, byte[] postData)
public WWW (string url, WWWForm form)
public WWW (string url)
很多方法呢,从文档中可以看到。
但是正在我看书的过程中发现有个方法已经被弃置了,所以特意写下笔记,增强记忆。
参考《Unity 3D/2D 手机游戏开发》一书自学的。
但遗憾在Unity5 的时候有方法被弃置,本人的思路将会根据该书来记录。
1.创建一个脚本,选C#,名为WebManager。
2.将脚本WebManager.cs 添加到一个对象上,即可触发脚本的事件。
3.开始编写代码。
3.1先编写一个界面。
using UnityE
using System.C
public class WebManager : MonoBehaviour {
//全局变量,用来接收信息提示,初始化为“Nothing”。
string m_info = "Nothing";
void OnGUI() {
GUI.BeginGroup (new Rect (Screen.width * 0.5f - 100, Screen.height * 0.5f - 100, 500, 200), "");
//创建一个标签,设置位置、大小,将接收信息提示的全局变量作为标签的文本内容。
GUI.Label (new Rect (10, 10, 400, 30), m_info);
//创建一个按钮,设置位置、大小,按钮上的标题为“Get Data”。
if (GUI.Button (new Rect (10, 50, 150, 30), "Get Data")) {
//这里写点击按钮所触发的行为、事件。
//创建一个按钮,设置位置、大小,按钮上的标题为“Post Data”。
if (GUI.Button (new Rect (10, 100, 150, 30), "Post Data")) {
//这里写点击按钮所触发的行为、事件。
GUI.EndGroup();
// Use this for initialization
void Start () {
// Update is called once per frame
void Update () {
首先就来个简单的方法吧。
Get请求是最简单的,所以一般简单的方法都是Get方法的。
3.2Get方法
先写下这个IGetData() 函数。需要注意的是该函数返回类型是迭代器 IEnumerator,通过这个可以进行协同调用。
IEnumerator IGetData() {
//使用Get方式访问HTTP地址
WWW www = new WWW ("http://yococoxc.vicp.cc:9999/test/userprint.php?username=yococo&password=");
//等待服务器的响应
//如果出现错误
if (www.error != null) {
//获取服务器的错误信息
m_info = www.
//获取服务器的响应文本
m_info = www.
然后需要将上面的函数在Get对应的按钮上设置好,以便触发。
if (GUI.Button (new Rect (10, 50, 150, 30), "Get Data")) {
StartCoroutine(IGetData());
StartCoroutine()方法的作用是启动协同程序,执行指定的方法,当然执行的方法的返回类型必须是IEnumerator。
关于程序所使用的PHP代码将会在最后列出。
3.3Post方法
Get方法就是如上那么简单,接下来就是Post方法,有些类似,但是比较麻烦,当然Post方法有很多优点的,默认你是知道的。
IEnumerator IPostData() {
Dictionary&string,string& headers = new Dictionary&string, string& ();
headers ["Content-Type"] = "application/x-www-form-urlencoded";
//将要发送的Post文本内容
string data = "username=yococo&password=";
//将文本转为byte数组
byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes (data);
//向HTTP服务器提交Post数据
WWW www = new WWW ("http://yococoxc.vicp.cc:9999/test/userprint.php", bs, headers);
//等待服务器的响应
//如果出现错误
if (www.error != null) {
//获取服务器的错误信息
m_info = www.
//获取服务器的响应文本
m_info = www.
特别提示:
用了 Dictionary 这个类,请引入 using System.Collections.Generic;
否则会出错。
然后按钮对应上执行的方法。
if (GUI.Button (new Rect (10, 100, 150, 30), "Post Data")) {
StartCoroutine(IPostData());
3.4弃置的方法。
public WWW (string url, byte[] postData, Hashtable headers)
被弃置了,这个编程中不罕见,有弃置就会有相对代替的方法,文档是关键。
3.5另外的Post写法,实现另外的方法。
IEnumerator IPostData() {
//将要发送的Post文本内容
string data = "username=yococo&password=";
//将文本转为byte数组
byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes (data);
//向HTTP服务器提交Post数据
WWW www = new WWW ("http://yococoxc.vicp.cc:9999/test/userprint.php", bs);
//等待服务器的响应
//如果出现错误
if (www.error != null) {
//获取服务器的错误信息
m_info = www.
//获取服务器的响应文本
m_info = www.
}此处少了添加头信息。
IEnumerator IPostData() {
WWWForm form = new WWWForm ();
//添加字段(键,值)
form.AddField ("username", "yococo");
form.AddField ("password", "");
//向HTTP服务器提交Post数据,提交表单
WWW www = new WWW ("http://yococoxc.vicp.cc:9999/test/userprint.php", form);
//等待服务器的响应
//如果出现错误
if (www.error != null) {
//获取服务器的错误信息
m_info = www.
//获取服务器的响应文本
m_info = www.
接下来就是PHP代码:
if (isset($_GET['username']) && isset($_GET['password'])) {
echo "GET -& username is " . $_GET['username'] . " and password is" . $_GET['password'];
} else if (isset($_POST['username']) && isset($_POST['password'])) {
echo "POST -& username is " . $_POST['username'] . " and password is" . $_POST['password'];
echo "error";
作者:木子才
iOS开发者俱乐部
有空可以加入这里一起探讨问题,由于群小,请输入验证信息。
没有更多推荐了,游戏蛮牛学习群(纯技术交流,不闲聊):
扫一扫,访问微社区
后使用快捷导航没有帐号?
签到成功!您今天第{todayrank}个签到,签到排名竞争激烈,记得每天都来签到哦!已连续签到:{constant}天,累计签到:{days}天
当前位置: &
查看: 10712|回复: 24
Unity3D使用串口与单片机等进行数据传输【转的】
本帖为抢楼帖,欢迎抢楼!&
71540/5000排名<font color="#FF昨日变化1主题帖子积分
日久生情, 积分 1540, 距离下一级还需 3460 积分
日久生情, 积分 1540, 距离下一级还需 3460 积分
蛮牛币2725
在线时间416 小时
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
才可以下载或查看,没有帐号?
使用串口与单片机等进行数据传输
一个简单的例子:(接收一个字节)
[csharp] view plaincopy
using UnityE& &using System.C& &using S& &using System.T& &using System.Collections.G& &using System.ComponentM& &using System.IO.P& &using System.Text.RegularE& &using System.T& &&&&&public class tmp : MonoBehaviour& &{& && & private SerialP& && & private Thread recvT& && & // Use this for initialization& && & void Start()& && & {& & & && &&&sp = new SerialPort(&COM1&, 9600, Parity.None, 8, StopBits.One);& && && &&&//串口初始化&&& && &&&if (!sp.IsOpen)&&& && &&&{&&& && && && &sp.Open();& && && &&&}&&& && &&&recvThread = new Thread(ReceiveOneByte); //该线程接收一个字节&&& && &&&recvThread.Start();& && & }& && & void Update()& && & {&&& && &&&//...&&& & }&&& && && & private void ReceiveOneByte()& && & {& && && && && &&&try& && && &&&{& && && && && &Byte[] buf = new Byte[1];& && && && && &string sbReadline2str = string.E& && && && && &if (sp.IsOpen)& && && && && && & sp.Read(buf, 0, 1);& && && &&&}&&& && &&&catch (Exception ex)& && && &&&{& && && && && &Debug.Log(ex);& && && &&&}&&& & }& &&&& & /* private void SendSerialPortData(string data) //发送一个字节 & &&&{&&& && && &if(sp.IsOpen)&&& && && &{&&& && && && & sp.WriteLine(data);&&& && && &}&&& &&&}&&& & */&&& & void OnApplicationQuit()& && & {& && && &&&sp.Close();& && & }& &}&&
Arduino+MPU6050提供姿态数据由Unity3D实时显示
Arduino端:1.准备:
与MPU6050的物理连接:A4---SDA A5---SCLVCC---3V3GND---GNDGND---ADD
Arduino IDE(我这用的是1.0.5)
库文件:https://github.com/jrowberg/i2cdevlib&&下载后本次需要的是MPU6050和I2Cdev两个文件夹,将它们拷贝进IDE的安装目录下的libraries\文件夹下
代码可由MPU6050库自带的Example中的“MPU6050_DMP6”改写(该Example还可用于测试连接或元件是否正常工作)
改写内容有:
1.选择输出欧拉角功能
2.去除其它不必要输出和输入
3.修改输出格式如下:每一组欧拉角前加“!”,欧拉角内以“#”分隔
注:由该Example可获得MPU6050经DMP处理后的数据,包括四元数,欧拉角,加速度,具体获得那种数据,靠预处理来选择
最终代码:
[cpp] view plaincopy
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)&&// 6/21/2012 by Jeff Rowberg &&&&// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib&&//&&// Changelog:&&//& && & - added seamless Fastwire support&&//& && && && && &&&- added note about gyro calibration&&//& && & - added note about Arduino 1.0.1 + Leonardo compatibility error&&//& && & - improved FIFO overflow handling and simplified read process&&//& && & - completely rearranged DMP initialization code and simplification&&//& && & - pull gyro and accel data from FIFO packet instead of reading directly&&//& && & - fix broken FIFO read sequence and change interrupt detection to RISING&&//& && & - add gravity-compensated initial reference frame acceleration output&&//& && && && && &&&- add 3D math helper file to DMP6 example sketch&&//& && && && && &&&- add Euler output and Yaw/Pitch/Roll output formats&&//& && & - remove accel offset clearing for better results (thanks Sungon Lee)&&//& && & - fixed gyro sensitivity to be 2000 deg/sec instead of 250&&//& && & - basic DMP initialization working&&&&/* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2012 Jeff Rowberg
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the &Software&), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED &AS IS&, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================== */&&&&// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files&&// for both classes must be in the include path of your project&&#include &I2Cdev.h&&&&&#include &MPU6050_6Axis_MotionApps20.h&&&//#include &MPU6050.h& // not necessary if using MotionApps include file&&&&// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation&&// is used in I2Cdev.h&&#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&&& & #include &Wire.h&&&#endif&&&&// class default I2C address is 0x68&&// specific I2C addresses may be passed as a parameter here&&// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)&&// AD0 high = 0x69&&MPU6050&&//MPU6050 mpu(0x69); // &-- use for AD0 high&&&&/* ========================================================================= & &NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch & &depends on the MPU-6050's INT pin being connected to the Arduino's & &external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is & &digital I/O pin 2.
* ========================================================================= */&&&&/* ========================================================================= & &NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error & &when using Serial.write(buf, len). The Teapot output uses this method. & &The solution requires a modification to the Arduino USBAPI.h file, which & &is fortunately simple, but annoying. This will be fixed in the next IDE & &release. For more info, see these links:
& &http://arduino.cc/forum/index.php/topic,.html & &http://code.google.com/p/arduino/issues/detail?id=958
* ========================================================================= */&&&&&&&&// uncomment &OUTPUT_READABLE_QUATERNION& if you want to see the actual&&// quaternion components in a [w, x, y, z] format (not best for parsing&&// on a remote host such as Processing or something though)&&//#define OUTPUT_READABLE_QUATERNION&&&&// uncomment &OUTPUT_READABLE_EULER& if you want to see Euler angles&&// (in degrees) calculated from the quaternions coming from the FIFO.&&// Note that Euler angles suffer from gimbal lock (for more info, see&&// http://en.wikipedia.org/wiki/Gimbal_lock)&&#define OUTPUT_READABLE_EULER&&&&// uncomment &OUTPUT_READABLE_YAWPITCHROLL& if you want to see the yaw/&&// pitch/roll angles (in degrees) calculated from the quaternions coming&&// from the FIFO. Note this also requires gravity vector calculations.&&// Also note that yaw/pitch/roll angles suffer from gimbal lock (for&&// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)&&//#define OUTPUT_READABLE_YAWPITCHROLL&&&&// uncomment &OUTPUT_READABLE_REALACCEL& if you want to see acceleration&&// components with gravity removed. This acceleration reference frame is&&// not compensated for orientation, so +X is always +X according to the&&// sensor, just without the effects of gravity. If you want acceleration&&// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.&&//#define OUTPUT_READABLE_REALACCEL&&&&// uncomment &OUTPUT_READABLE_WORLDACCEL& if you want to see acceleration&&// components with gravity removed and adjusted for the world frame of&&// reference (yaw is relative to initial orientation, since no magnetometer&&// is present in this case). Could be quite handy in some cases.&&//#define OUTPUT_READABLE_WORLDACCEL&&&&// uncomment &OUTPUT_TEAPOT& if you want output that matches the&&// format used for the InvenSense teapot demo&&//#define OUTPUT_TEAPOT&&&&&&&&#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)&&bool blinkState =&&&&// MPU control/status vars&&bool dmpReady =&&// set true if DMP init was successful&&uint8_t mpuIntS& &// holds actual interrupt status byte from MPU&&uint8_t devS& && &// return status after each device operation (0 = success, !0 = error)&&uint16_t packetS& & // expected DMP packet size (default is 42 bytes)&&uint16_t fifoC& &&&// count of all bytes currently in FIFO&&uint8_t fifoBuffer[64]; // FIFO storage buffer&&&&// orientation/motion vars&&Q& && && &&&// [w, x, y, z]& && && &quaternion container&&VectorInt16& && && &// [x, y, z]& && && && &accel sensor measurements&&VectorInt16 aaR& &&&// [x, y, z]& && && && &gravity-free accel sensor measurements&&VectorInt16 aaW& & // [x, y, z]& && && && &world-frame accel sensor measurements&&VectorF& & // [x, y, z]& && && && &gravity vector&&float euler[3];& && && &// [psi, theta, phi]& & Euler angle container&&float ypr[3];& && && &&&// [yaw, pitch, roll]& &yaw/pitch/roll container and gravity vector&&&&// packet structure for InvenSense teapot demo&&uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };&&&&&&&&// ================================================================&&// ===& && && && && &INTERRUPT DETECTION ROUTINE& && && && && & ===&&// ================================================================&&&&volatile bool mpuInterrupt =& &&&// indicates whether MPU interrupt pin has gone high&&void dmpDataReady() {&&& & mpuInterrupt =&&}&&&&&&&&// ================================================================&&// ===& && && && && && && & INITIAL SETUP& && && && && && && &&&===&&// ================================================================&&&&void setup() {&&& & // join I2C bus (I2Cdev library doesn't do this automatically)&&& & #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&&& && &&&Wire.begin();&&& && &&&TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)&&& & #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE&&& && &&&Fastwire::setup(400, true);&&& & #endif&&&&& & // initialize serial communication&&& & // (115200 chosen because it is required for Teapot Demo output, but it's&&& & // really up to you depending on your project)&&& & Serial.begin(115200);&&& & while (!Serial); // wait for Leonardo enumeration, others continue immediately&&&&& & // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio&&& & // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to&&& & // the baud timing being too misaligned with processor ticks. You must use&&& & // 38400 or slower in these cases, or use some kind of external separate&&& & // crystal solution for the UART timer.&&&&& & // initialize device&&& &// Serial.println(F(&Initializing I2C devices...&));&&& & mpu.initialize();&&&&& & // verify connection&&& &// Serial.println(F(&Testing device connections...&));&&&&//&&Serial.println(mpu.testConnection() ? F(&MPU6050 connection successful&) : F(&MPU6050 connection failed&));&&&&& & // wait for ready&&& &// Serial.println(F(&\nSend any character to begin DMP programming and demo: &));&&&&//&&while (Serial.available() && Serial.read()); // empty buffer&& //& &while (!Serial.available());& && && && && &&&// wait for data&& //& &while (Serial.available() && Serial.read()); // empty buffer again&&&&& & // load and configure the DMP&&&&//&&Serial.println(F(&Initializing DMP...&));&&& & devStatus = mpu.dmpInitialize();&&&&& & // supply your own gyro offsets here, scaled for min sensitivity&&& & mpu.setXGyroOffset(220);&&& & mpu.setYGyroOffset(76);&&& & mpu.setZGyroOffset(-85);&&& & mpu.setZAccelOffset(1788); // 1688 factory default for my test chip&&&&& & // make sure it worked (returns 0 if so)&&& & if (devStatus == 0) {&&& && &&&// turn on the DMP, now that it's ready&&& &&&//& &Serial.println(F(&Enabling DMP...&));&&& && &&&mpu.setDMPEnabled(true);&&&&& && &&&// enable Arduino interrupt detection&&& &&&//& &Serial.println(F(&Enabling interrupt detection (Arduino external interrupt 0)...&));&&& && &&&attachInterrupt(0, dmpDataReady, RISING);&&& && &&&mpuIntStatus = mpu.getIntStatus();&&&&& && &&&// set our DMP Ready flag so the main loop() function knows it's okay to use it&&& & //& & Serial.println(F(&DMP ready! Waiting for first interrupt...&));&&& && &&&dmpReady =&&&&& && &&&// get expected DMP packet size for later comparison&&& && &&&packetSize = mpu.dmpGetFIFOPacketSize();&&& & } else {&&& && &&&// ERROR!&&& && &&&// 1 = initial memory load failed&&& && &&&// 2 = DMP configuration updates failed&&& && &&&// (if it's going to break, usually the code will be 1)&&& && &&&Serial.print(F(&DMP Initialization failed (code &));&&& && &&&Serial.print(devStatus);&&& && &&&Serial.println(F(&)&));&&& & }&&&&& & // configure LED for output&&& & pinMode(LED_PIN, OUTPUT);&&}&&&&&&&&// ================================================================&&// ===& && && && && && &&&MAIN PROGRAM LOOP& && && && && && && &===&&// ================================================================&&&&void loop() {&&& & // if programming failed, don't try to do anything&&& & if (!dmpReady)&&&&& & // wait for MPU interrupt or extra packet(s) available&&& & while (!mpuInterrupt && fifoCount & packetSize) {&&& && &&&// other program behavior stuff here&&& && &&&// .&&& && &&&// .&&& && &&&// .&&& && &&&// if you are really paranoid you can frequently test in between other&&& && &&&// stuff to see if mpuInterrupt is true, and if so, && from the&&& && &&&// while() loop to immediately process the MPU data&&& && &&&// .&&& && &&&// .&&& && &&&// .&&& & }&&&&& & // reset interrupt flag and get INT_STATUS byte&&& & mpuInterrupt =&&& & mpuIntStatus = mpu.getIntStatus();&&&&& & // get current FIFO count&&& & fifoCount = mpu.getFIFOCount();&&&&& & // check for overflow (this should never happen unless our code is too inefficient)&&& & if ((mpuIntStatus & 0x10) || fifoCount == 1024) {&&& && &&&// reset so we can continue cleanly&&& && &&&mpu.resetFIFO();&&& && &&&Serial.println(F(&FIFO overflow!&));&&&&& & // otherwise, check for DMP data ready interrupt (this should happen frequently)&&& & } else if (mpuIntStatus & 0x02) {&&& && &&&// wait for correct available data length, should be a VERY short wait&&& && &&&while (fifoCount & packetSize) fifoCount = mpu.getFIFOCount();&&&&& && &&&// read a packet from FIFO&&& && &&&mpu.getFIFOBytes(fifoBuffer, packetSize);&&& && && & & && &&&// track FIFO count here in case there is & 1 packet available&&& && &&&// (this lets us immediately read more without waiting for an interrupt)&&& && &&&fifoCount -= packetS&&&&& && &&&#ifdef OUTPUT_READABLE_QUATERNION&&& && && && &// display quaternion values in easy matrix form: w x y z&&& && && && &mpu.dmpGetQuaternion(&q, fifoBuffer);&&& && && && &Serial.print(&!&);&&& && && && &Serial.print(q.x);&&& && && && &Serial.print(&#&);&&& && && && &Serial.print(q.y);&&& && && && &Serial.print(&#&);&&& && && && &Serial.print(q.z);&&& && && && &Serial.print(&#&);&&& && && && &Serial.print(q.w);&&& && &&&#endif&&&&& && &&&#ifdef OUTPUT_READABLE_EULER&&& && && && &// display Euler angles in degrees&&& && && && &mpu.dmpGetQuaternion(&q, fifoBuffer);&&& && && && &mpu.dmpGetEuler(euler, &q);&&& && && && &Serial.print(&!&);&&& && && && &Serial.print(euler[0] * 180/M_PI);&&& && && && &Serial.print(&#&);&&& && && && &Serial.print(euler[1] * 180/M_PI);&&& && && && &Serial.print(&#&);&&& && && && &Serial.print(euler[2] * 180/M_PI);&&& && &&&#endif&&&&& && &&&#ifdef OUTPUT_READABLE_YAWPITCHROLL&&& && && && &// display Euler angles in degrees&&& && && && &mpu.dmpGetQuaternion(&q, fifoBuffer);&&& && && && &mpu.dmpGetGravity(&gravity, &q);&&& && && && &mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);&&& && && && &Serial.print(&!&);&&& && && && &Serial.print(ypr[0] * 180/M_PI);&&& && && && &Serial.print(&#&);&&& && && && &Serial.print(ypr[1] * 180/M_PI);&&& && && && &Serial.print(&#&);&&& && && && &Serial.print(ypr[2] * 180/M_PI);&&& && &&&#endif&&&&& && &&&#ifdef OUTPUT_READABLE_REALACCEL&&& && && && &// display real acceleration, adjusted to remove gravity&&& && && && &mpu.dmpGetQuaternion(&q, fifoBuffer);&&& && && && &mpu.dmpGetAccel(&aa, fifoBuffer);&&& && && && &mpu.dmpGetGravity(&gravity, &q);&&& && && && &mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);&&& && && && &Serial.print(&areal\t&);&&& && && && &Serial.print(aaReal.x);&&& && && && &Serial.print(&\t&);&&& && && && &Serial.print(aaReal.y);&&& && && && &Serial.print(&\t&);&&& && && && &Serial.println(aaReal.z);&&& && &&&#endif&&&&& && &&&#ifdef OUTPUT_READABLE_WORLDACCEL&&& && && && &// display initial world-frame acceleration, adjusted to remove gravity&&& && && && &// and rotated based on known orientation from quaternion&&& && && && &mpu.dmpGetQuaternion(&q, fifoBuffer);&&& && && && &mpu.dmpGetAccel(&aa, fifoBuffer);&&& && && && &mpu.dmpGetGravity(&gravity, &q);&&& && && && &mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);&&& && && && &mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);&&& && && && &Serial.print(&aworld\t&);&&& && && && &Serial.print(aaWorld.x);&&& && && && &Serial.print(&\t&);&&& && && && &Serial.print(aaWorld.y);&&& && && && &Serial.print(&\t&);&&& && && && &Serial.println(aaWorld.z);&&& && &&&#endif&&& && && && &&&#ifdef OUTPUT_TEAPOT&&& && && && &// display quaternion values in InvenSense Teapot demo format:&&& && && && &teapotPacket[2] = fifoBuffer[0];&&& && && && &teapotPacket[3] = fifoBuffer[1];&&& && && && &teapotPacket[4] = fifoBuffer[4];&&& && && && &teapotPacket[5] = fifoBuffer[5];&&& && && && &teapotPacket[6] = fifoBuffer[8];&&& && && && &teapotPacket[7] = fifoBuffer[9];&&& && && && &teapotPacket[8] = fifoBuffer[12];&&& && && && &teapotPacket[9] = fifoBuffer[13];&&& && && && &Serial.write(teapotPacket, 14);&&& && && && &teapotPacket[11]++; // packetCount, loops at 0xFF on purpose&&& && &&&#endif&&&&& && &&&// blink LED to indicate activity&&& && &&&blinkState = !blinkS&&& && &&&digitalWrite(LED_PIN, blinkState);&&& & }&&}&&
Unity3D端:
[csharp] view plaincopy
using UnityE& &using System.C& &using S& &using System.T& &using System.Collections.G& &using System.ComponentM& &using System.IO.P& &using System.Text.RegularE& &using System.T& &&&&&public class com : MonoBehaviour& &{& &&span style=&white-space:pre&&&&&/span&public GameO//目标操作物体&&& & private SerialP& && & private Thread recvT& && & float x,y,z;//存放欧拉角&&& & // Use this for initialization& && & void Start()& && & {& && && &&&Debug.Log(&start&);& && && &&&sp = new SerialPort(&COM1&, 115200, Parity.None, 8, StopBits.One);& && && &&&//串口初始化&&& && &&&if (!sp.IsOpen)&&& && &&&{&&& && && && &sp.Open();& && && &&&}&&& && &&&recvThread = new Thread(ReceiveData);& && && &&&recvThread.Start();& && & }& &&&&&& & // Update is called once per frame& && & void Update()& && & {& && && &&&Debug.Log(x+&&&&+y+&&&&+z);&&& && &&&//更新姿态&&& && &&&target.transform.eulerAngles=new Vector3(x,y,z);&&& & }&&& && && & private void ReceiveData()& && & {& && && &&&char[] spil=&#&.ToCharArray();//“#”为串口传入一份数据内的分隔符,数据间的分隔符为“!”(ASICII为33)&&& && &&&char[] sbuf = new char[1024];&&& && &&&try& && && &&&{& && && && && &Byte[] buf = new Byte[1];& && && && && &string sbReadline2str = string.E& && && && && &if (sp.IsOpen) sp.Read(buf, 0, 1);& && && && && &&&& && && && &if (buf.Length == 0)& && && && && &{& && && && && && && && && && && &}&&& && && && &else if(buf[0]==33){//第一次找到数据头标志&&& && && && && & int i=0;&&& && && && && & while(true){//不断读取欧拉角&&& && && && && && &&&sp.Read(buf, 0, 1);//读一个字节&&& && && && && && &&&if(buf[0]!=33)//该份欧拉角未结束&&& && && && && && && && &{&&& && && && && && && && && & //保存该字节&&& && && && && && && && && & sbuf=(char)buf[0];&&& && && && && && && && && & i++;&&& && && && && && && && &}else{&&& && && && && && && && && & String s=new String(sbuf,0,i);&&& && && && && && && && && & String []ss=s.Split(spil);&&& && && && && && && && && & i=0;&&& && && && && && && && && & //更新X,Y,Z&&& && && && && && && && && & if(ss.Length==3)&&& && && && && && && && && & {&&& && && && && && && && && && &&&x=float.Parse(ss[0]);&&& && && && && && && && && && &&&y=float.Parse(ss[1]);&&& && && && && && && && && && &&&z=float.Parse(ss[2]);&&& && && && && && && && && & }&&& && && && && && && && && & //接着读取下一组欧拉角&&& && && && && && && && &}&&& && && && && & }&&& && && && &&&& && && && &}&&&&& && &&&}&&& && &&&catch (Exception ex)& && && &&&{& && && && && &Debug.Log(ex);& && && &&&}&&& & }& &&&& &&& private void SendSerialPortData(string data)& & {& && &&&if(sp.IsOpen)& && &&&{& && && && &sp.WriteLine(data);& && &&&}& & }& && & & & void OnApplicationQuit()& && & {& && && &&&sp.Close();& && & }& &}&&
using system.io.unity3d byte[] 转unity 串口发送数据;unity3d 串口 拒绝访问;unity 串口通信;math library for unity教程;unity3d串口通信;unity串口;unity3d接收串口信息;unity3d 串口 发送;unity3d 获得unity3d input.unity3d 如何输出即时数据;arduino unity3d
请重新排版一下,代码放进代码块里!&
每日推荐:
72284/5000排名<font color="#FF昨日变化主题帖子积分
日久生情, 积分 2284, 距离下一级还需 2716 积分
日久生情, 积分 2284, 距离下一级还需 2716 积分
蛮牛币4145
在线时间586 小时
受教了。还可以适当排版下
每日推荐:
18/50排名<font color="#FF昨日变化59主题帖子积分
注册看看, 积分 8, 距离下一级还需 42 积分
注册看看, 积分 8, 距离下一级还需 42 积分
在线时间0 小时
RE:&&unity3D使用串口与单片机等进行数据传输&&感谢楼主无私分享
每日推荐:
4423/500排名<font color="#FF昨日变化5主题帖子积分
四处流浪, 积分 423, 距离下一级还需 77 积分
四处流浪, 积分 423, 距离下一级还需 77 积分
在线时间60 小时
感谢楼主无私分享!!!!!
每日推荐:
271/150排名<font color="#FF昨日变化27主题帖子积分
初来乍到, 积分 71, 距离下一级还需 79 积分
初来乍到, 积分 71, 距离下一级还需 79 积分
在线时间35 小时
你好,我最近也在研究mpu9150,制作的方法和你是一样的,遇到了一些小问题,想请教一下你,如果方便加下QQ:,谢谢
每日推荐:
13/50主题帖子积分
注册看看, 积分 3, 距离下一级还需 47 积分
注册看看, 积分 3, 距离下一级还需 47 积分
在线时间0 小时
你这样写肯定会出错,close线程和open线程会冲突
每日推荐:
130/50排名<font color="#FF昨日变化28主题帖子积分
注册看看, 积分 30, 距离下一级还需 20 积分
注册看看, 积分 30, 距离下一级还需 20 积分
在线时间14 小时
你这样写肯定会出错,close线程和open线程会冲突
你好,我最近在用U3D与串口通讯,用法和上面一样,但是发现有时候会报错,在SerialPort.Open()这个方法在切换场景之后再打开会报IOException:访问拒绝这个错误。我感觉是我切换场景之后很快又切换到使用串口通讯时会遇到这个错误。请问应该怎么解决?谢谢~~
每日推荐:
130/50排名<font color="#FF昨日变化28主题帖子积分
注册看看, 积分 30, 距离下一级还需 20 积分
注册看看, 积分 30, 距离下一级还需 20 积分
在线时间14 小时
楼主,我最近在用U3D与串口通讯,用法和上面一样,但是发现有时候会报错,在SerialPort.Open()这个方法在切换场景之后再打开会报IOException:访问拒绝这个错误。我感觉是我切换场景之后很快又切换到使用串口通讯时会遇到这个错误。请问应该怎么解决?谢谢~~
每日推荐:
73363/5000排名<font color="#FF昨日变化1主题帖子积分
日久生情, 积分 3363, 距离下一级还需 1637 积分
日久生情, 积分 3363, 距离下一级还需 1637 积分
蛮牛币3703
在线时间1609 小时
楼主,我最近在用U3D与串口通讯,用法和上面一样,但是发现有时候会报错,在SerialPort.Open()这个方法在切 ...
现在你这个问题是怎么解决的
[]: lovedaizhenzhen 乐于助人,奖励 3
每日推荐:
130/50排名<font color="#FF昨日变化28主题帖子积分
注册看看, 积分 30, 距离下一级还需 20 积分
注册看看, 积分 30, 距离下一级还需 20 积分
在线时间14 小时
现在你这个问题是怎么解决的
就是只实例化一次,切换场景的时候,用DontDestroyOnLoad方法,把代码挂在一个对象上面,然后就可以了。
每日推荐:
130/50排名<font color="#FF昨日变化28主题帖子积分
注册看看, 积分 30, 距离下一级还需 20 积分
注册看看, 积分 30, 距离下一级还需 20 积分
在线时间14 小时
现在你这个问题是怎么解决的
就是只实例化一次,切换场景的时候,用DontDestroyOnLoad方法,把代码挂在一个对象上面,然后就可以了。
[]: jane3von 乐于助人,奖励 3
每日推荐:
73363/5000排名<font color="#FF昨日变化1主题帖子积分
日久生情, 积分 3363, 距离下一级还需 1637 积分
日久生情, 积分 3363, 距离下一级还需 1637 积分
蛮牛币3703
在线时间1609 小时
就是只实例化一次,切换场景的时候,用DontDestroyOnLoad方法,把代码挂在一个对象上面,然后就可以了。 ...
能把你的串口通信那部分让我看看吗,我现在在串口通信的时候一直都是超时,一个数据也读不出来
每日推荐:
130/50排名<font color="#FF昨日变化28主题帖子积分
注册看看, 积分 30, 距离下一级还需 20 积分
注册看看, 积分 30, 距离下一级还需 20 积分
在线时间14 小时
能把你的串口通信那部分让我看看吗,我现在在串口通信的时候一直都是超时,一个数据也读不出来 ...
这是我项目中直接拿出来的写串口通信收发数据的脚本,你一直超时应该是你读的时候用的方法不对吧。希望可以帮到你~~
using System.T
using System.ComponentM
using System.Text.RegularE
using System.T
#region Using directives
//Other libraries
using System.Collections.G
using System.ComponentM
//Serial Port library.
using System.IO.P
#endregion
public class tmp : MonoBehaviour
& & public static SerialP
& & void Start()
& && &&&Screen.showCursor = // 鼠标隐藏
& && &&&if (static_.cout == 0)
& && && && &System.Diagnostics.Process.Start(Application.dataPath + &/ExprotToTXT_ComName.exe&);
& && && && &static_.cout++;
& && && && &//static_.getPortName();
& && && && &//if (static_.strPortName == &&)
& && && && &//{
& && && && &//& & Debug.Log(&端口号为空!&);
& && && && &//& & Application.Quit();
& && && && &//}
& && && && &if (static_.strPortName != && && sp == null)
& && && && &{
& && && && && & sp = new SerialPort(static_.strPortName, 19200, Parity.None, 8, StopBits.One);//19200
& && && && && & Debug.Log(&new SerialPort&);
& && && && &}
& && && && &if (!sp.IsOpen)
& && && && &{
& && && && && & try
& && && && && & {
& && && && && && &&&try
& && && && && && &&&{
& && && && && && && && &sp.Open();
& && && && && && && && &Debug.Log(&opened!!1&);
& && && && && && &&&}
& && && && && && &&&catch (Exception ex)
& && && && && && &&&{
& && && && && && && && &Debug.Log(ex);
& && && && && && &&&}
& && && && && && &&&sp.ReadTimeout = 1;
& && && && && && &
& && && && && & }
& && && && && & catch (Exception ex)
& && && && && & {
& && && && && && &&&Debug.Log(&open error!&&& + ex);
& && && && && && &&&sp.Close();& && && && && && &
& && && && && & }
& && && && &}
& & public void FixedUpdate()
& && &&&static_.strRecvDt = ReceiveData();
& && &&&if (static_.strRecvDt.IndexOf(&_close!&,0)!=-1)
& && && && &Debug.Log(&_close! 登陆到auto_60&);
& && && && &SendSerialPortData(&_000!&);
& && && && &Application.LoadLevel(&0&);
& && &&&if (static_.strRecvDt.IndexOf(&_open!&, 0) != -1)
& && && && &Debug.Log(&_open! 登陆到1&);
& && && && &SendSerialPortData(&_000!&);
& && && && &Application.LoadLevel(&0&);
& && && && && && &&&
& & public string ReceiveData()
& && &&&string message = &&;
& && &&&Byte[] buf = new Byte[1000];
& && &&&if (sp.IsOpen)
& && && && &sp.Read(buf,0,1000);
& && && &if(buf.Length&0)
& && && &&&message=System.Text.Encoding.Default.GetString(buf);
& && &&&//bool start =
& && &&&//string message = &&;
& && &&&//Byte[] buf = new Byte[1];
& && &&&//try
& && &&&//{
& && &&&//& & if (sp.IsOpen)
& && &&&//& && &&&sp.Read(buf,0,1);
& && &&&//& &// if(buf.Length&0)
& && &&&//& &//message=System.Text.Encoding.Default.GetString(buf);
& && &&&//& & if (System.Text.Encoding.Default.GetString(buf) == &_&)
& && &&&//& & {
& && &&&//& && &&&message = System.Text.Encoding.Default.GetString(buf);
& && &&&//& && &&&start =
& && &&&//& && &&&while (start)
& && &&&//& && &&&{
& && &&&//& && && && &if (sp.IsOpen)
& && &&&//& && && && && & sp.Read(buf, 0, 1);
& && &&&//& && && && &if (System.Text.Encoding.Default.GetString(buf) == &!&)
& && &&&//& && && && &{
& && &&&//& && && && && & message = message + System.Text.Encoding.Default.GetString(buf);
& && &&&//& && && && && & start =& && && && && && && &&&
& && &&&//& && && && && & Debug.Log(&ReceiveData: & + message);& && && && && && && &&&
& && && && && && && &
& && &&&//& && && && && &
& && &&&//& && && && &}
& && &&&//& && && && &message = message + System.Text.Encoding.Default.GetString(buf);
& && &&&//& && &&&}
& && &&&//& & }
& && &&&//}
& && &&&//catch (Exception ex)
& && &&&//{
& && &&&//& & message = &&;
& && &&&//& & //Debug.Log(&ReceiveData___&&& + ex);
& && &&&//}
& && &&&//
& & public void SendSerialPortData(string data)
& && &&&if (sp.IsOpen)
& && && &&&// Debug.Log(data);
& && && && &sp.WriteLine(data);
& & void OnApplicationQuit()
& && & // isStartThread =
& && & // StartCoroutine(ClosePort());
& && &&&if(sp!=null)
& && && && &if (sp.IsOpen)
& && && && && & sp.Close();
& && &&&Debug.Log(&close ClosePort!&);
& & IEnumerator ClosePort()&&//该方法为关闭串口的方法,当程序退出或是离开该页面或是想停止串口时调用。
& && & // isStartThread =&&//停止掉FixedUpdate里面的两个线程的调用
& && &&&yield return new WaitForSeconds(1);&&//等一秒钟,让两个线程确实停止之后在执行Close方法
& && &&&Debug.Log(&close thread!&);
&&public&&void show_1()
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_011!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& && &&&}& && &
& & public void show_2()
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_101!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& && &&&}& && && && && &
& & public void show_3()
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_110!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& & public void show_1_100()
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_011!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& && &&&}& && &
& & public void show_2_100()
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_101!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& && &&&}& && &&&
& & public void show_3_100()
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_110!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& && &&&}& && &
& & public void show_4_100()
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_111!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& && &&&}& && &
& & public void show_5_100()
& & {& && &
& && &&&if (sp.IsOpen)
& && && && &SendSerialPortData(&_000!&);
& && &&&else
& && && && &Debug.Log(&端口没打开!&);
& && &&&}& && &
[]: jane3von 捡了钱没交公 蛮牛币 降了 1
每日推荐:
130/50排名<font color="#FF昨日变化28主题帖子积分
注册看看, 积分 30, 距离下一级还需 20 积分
注册看看, 积分 30, 距离下一级还需 20 积分
在线时间14 小时
本帖最后由 jane3von 于
16:27 编辑
能把你的串口通信那部分让我看看吗,我现在在串口通信的时候一直都是超时,一个数据也读不出来 ...
这是我项目中直接拿出来的写串口通信收发数据的脚本,你一直超时应该是你读的时候用的方法不对吧。希望可以帮到你~~
public class tmp : MonoBehaviour
& & public static SerialP
& & void Start()
& && &&&Screen.showCursor = // 鼠标隐藏
& && &&&if (static_.cout == 0)
& && && && &System.Diagnostics.Process.Start(Application.dataPath + &/ExprotToTXT_ComName.exe&);
& && && && &static_.cout++;
& && && && &//static_.getPortName();
& && && && &//if (static_.strPortName == &&)
& && && && &//{
& && && && &//& & Debug.Log(&端口号为空!&);
& && && && &//& & Application.Quit();
& && && && &//}
& && && && &if (static_.strPortName != && && sp == null)
& && && && &{
& && && && && & sp = new SerialPort(static_.strPortName, 19200, Parity.None, 8, StopBits.One);//19200
& && && && && & Debug.Log(&new SerialPort&);
& && && && &}
& && && && &if (!sp.IsOpen)
& && && && &{
& && && && && & try
& && && && && & {
& && && && && && &&&try
& && && && && && &&&{
& && && && && && && && &sp.Open();
& && && && && && && && &Debug.Log(&opened!!1&);
& && && && && && &&&}
& && && && && && &&&catch (Exception ex)
& && && && && && &&&{
& && && && && && && && &Debug.Log(ex);
& && && && && && &&&}
& && && && && && &&&sp.ReadTimeout = 1;
& && && && && && &
& && && && && & }
& && && && && & catch (Exception ex)
& && && && && & {
& && && && && && &&&Debug.Log(&open error!&&& + ex);
& && && && && && &&&sp.Close();& && && && && && &
& && && && && & }
& && && && &}
& & public void FixedUpdate()
& && &&&static_.strRecvDt = ReceiveData();
& && &&&if (static_.strRecvDt.IndexOf(&_close!&,0)!=-1)
& && && && &Debug.Log(&_close! 登陆到auto_60&);
& && && && &SendSerialPortData(&_000!&);
& && && && &Application.LoadLevel(&0&);
& && &&&if (static_.strRecvDt.IndexOf(&_open!&, 0) != -1)
& && && && &Debug.Log(&_open! 登陆到1&);
& && && && &SendSerialPortData(&_000!&);
& && && && &Application.LoadLevel(&0&);
& && && && && && &&&
& & public string ReceiveData()
& && &&&string message = &&;
& && &&&Byte[] buf = new Byte[1000];
& && &&&if (sp.IsOpen)
& && && && &sp.Read(buf,0,1000);
& && && &if(buf.Length&0)
& && && &&&message=System.Text.Encoding.Default.GetString(buf);
& && &&&//bool start =
& && &&&//string message = &&;
& && &&&//Byte[] buf = new Byte[1];
& && &&&//try
& && &&&//{
& && &&&//& & if (sp.IsOpen)
& && &&&//& && &&&sp.Read(buf,0,1);
& && &&&//& &// if(buf.Length&0)
& && &&&//& &//message=System.Text.Encoding.Default.GetString(buf);
& && &&&//& & if (System.Text.Encoding.Default.GetString(buf) == &_&)
& && &&&//& & {
& && &&&//& && &&&message = System.Text.Encoding.Default.GetString(buf);
& && &&&//& && &&&start =
& && &&&//& && &&&while (start)
& && &&&//& && &&&{
& && &&&//& && && && &if (sp.IsOpen)
& && &&&//& && && && && & sp.Read(buf, 0, 1);
& && &&&//& && && && &if (System.Text.Encoding.Default.GetString(buf) == &!&)
& && &&&//& && && && &{
& && &&&//& && && && && & message = message + System.Text.Encoding.Default.GetString(buf);
& && &&&//& && && && && & start =& && && && && && && &&&
& && &&&//& && && && && & Debug.Log(&ReceiveData: & + message);& && && && && && && &&&
& && && && && && && &
& && &&&//& && && && && &
& && &&&//& && && && &}
& && &&&//& && && && &message = message + System.Text.Encoding.Default.GetString(buf);
& && &&&//& && &&&}
& && &&&//& & }
& && &&&//}
& && &&&//catch (Exception ex)
& && &&&//{
& && &&&//& & message = &&;
& && &&&//& & //Debug.Log(&ReceiveData___&&& + ex);
& && &&&//}
& && &&&//
& & public void SendSerialPortData(string data)
& && &&&if (sp.IsOpen)
& && && &&&// Debug.Log(data);
& && && && &sp.WriteLine(data);
& & void OnApplicationQuit()
& && & // isStartThread =
& && & // StartCoroutine(ClosePort());
& && &&&if(sp!=null)
& && && && &if (sp.IsOpen)
& && && && && & sp.Close();
& && &&&Debug.Log(&close ClosePort!&);
& & IEnumerator ClosePort()&&//该方法为关闭串口的方法,当程序退出或是离开该页面或是想停止串口时调用。
& && & // isStartThread =&&//停止掉FixedUpdate里面的两个线程的调用
& && &&&yield return new WaitForSeconds(1);&&//等一秒钟,让两个线程确实停止之后在执行Close方法
& && &&&Debug.Log(&close thread!&);
每日推荐:
73363/5000排名<font color="#FF昨日变化1主题帖子积分
日久生情, 积分 3363, 距离下一级还需 1637 积分
日久生情, 积分 3363, 距离下一级还需 1637 积分
蛮牛币3703
在线时间1609 小时
这是我项目中直接拿出来的写串口通信收发数据的脚本,你一直超时应该是你读的时候用的方法不对吧。希望可 ...
我读每次按照一个字节,或者指定字节或者一行都试过了。还有,我在判断缓冲区有多少字节就是byteread 函数时报错。这是为什么
每日推荐:
购买游戏蛮牛书籍

我要回帖

更多关于 unity3d人才过剩 的文章

 

随机推荐