简单unity协程优化方案
来源:互联网 发布:数据库爆破 原理 编辑:程序博客网 时间:2024/06/06 04:09
做三消项目需要做一个提示用户哪个格子可以消除的功能,需要对整个棋盘进行遍历。
原来没用协程的代码
public void GetTip(){GameObject go1, go2; int[] way = { 1, -1, -10, 10 }; int max = (xl - 1) * 10 + yl - 1; for (int x = 0; x < xl; x += 2) { for (int y = 0; y < yl; y++) { int gid = GetGridID(x, y); for (int i = 0; i <= 3; i++) { int newGid = gid + way[i]; if (newGid <= max && newGid >= 0 && newGid % 10 < yl) { Swap(ref DicGrid[newGid].GridType, ref DicGrid[gid].GridType); if (ComparatorTip(newGid)) { go1 = DicGrid[gid].gameObject; go2 = DicGrid[newGid].gameObject; HighLight(go1); HighLight(go2); Swap(ref DicGrid[newGid].GridType, ref DicGrid[gid].GridType); return; } else Swap(ref DicGrid[newGid].GridType, ref DicGrid[gid].GridType); } } } }return ;}
代码很多,只看重点,代码里的二重循环对游戏主循环有很大影响,每次用户点击按钮都要卡一下,但是unity不允许在这种地方用多线程,所以,只能改成协程,让这个功能分几个帧完成,就可以感觉不到卡顿。
修改后的代码
public void GetTipGo() { StartCoroutine("IGetTipGo"); } IEnumerator IGetTipGo() { GameObject go1, go2; int[] way = { 1, -1, -10, 10 }; int max = (xl - 1) * 10 + yl - 1; for (int x = 0; x < xl; x += 2) { for (int y = 0; y < yl; y++) { int gid = GetGridID(x, y); for (int i = 0; i <= 3; i++) { int newGid = gid + way[i]; if (newGid <= max && newGid >= 0 && newGid % 10 < yl) { yield return 0; Swap(ref DicGrid[newGid].GridType, ref DicGrid[gid].GridType); if (ComparatorTip(newGid)) { yield return 0; go1 = DicGrid[gid].gameObject; go2 = DicGrid[newGid].gameObject; HightLight(go1); HighLight(go2); Swap(ref DicGrid[newGid].GridType, ref DicGrid[gid].GridType); StopCoroutine("IGetTipGo"); } else Swap(ref DicGrid[newGid].GridType, ref DicGrid[gid].GridType); } } } } StopCoroutine("IGetTipGo"); }
用两个yield return 0;将几个比较耗时间的运算用帧分开,原来的return改为StopCoroutine();
这样就可以释放主循环的压力了。
PS:进阶技巧
协程与多线程的结合
参考博客
http://blog.csdn.net/laipixiaoxi/article/details/51890903
阅读全文
0 0
- 简单unity协程优化方案
- unity 优化方案
- Unity内存优化方案集合
- Unity中一些优化方案
- Unity项目图片纹理优化方案
- [Unity优化]图片纹理压缩方案
- Unity手游简单优化
- 【Unity优化】如何实现Unity编辑器中的协程
- 【Unity优化】如何实现Unity编辑器中的协程
- Unity游戏性能优化时的截图方案分析
- Unity中简单的优化物理系统
- 数据库sql简单的优化方案
- unity中的简单的协程用法。
- unity游戏性能优化之简单内存优化
- Unity 协程运行时的监控和优化
- Unity 协程运行时的监控和优化
- Unity 优化
- Unity 优化
- Eclipse创建maven-webapp项目问题汇总及解决方法
- 修改trunk到access
- Java框架--- hibernate 框架
- 机器学习:Bias(偏差),Error(误差),和Variance(方差)
- HashSet去重原理
- 简单unity协程优化方案
- Java的集合与散列
- day48_Redis+Jedis。Java操作Redis、其他各种常用配置命令 总结【后面会用到今天搭建的环境-便于复习)】
- 手机号、邮箱或者用户名登录的实现方法
- HDU 3605 Escape(多重匹配||状压缩点的网络流)
- 倒序打印双链表算法
- Java 传值传引用
- 0,NULL,nullptr区别
- 第二周周中总结