当前位置: 首页 > news >正文

从yield return到状态机:用C#控制台程序手写一个简易Unity协程

从yield return到状态机:用C#控制台程序手写一个简易Unity协程

在游戏开发领域,Unity引擎的协程(Coroutine)机制因其优雅的异步处理能力而备受开发者青睐。但你是否好奇过,这个看似神奇的"暂停与恢复"功能背后究竟隐藏着怎样的实现原理?本文将带领你脱离Unity环境,仅用C#控制台程序从零构建一个简易协程系统,深入探索迭代器与状态机的精妙配合。

1. 协程的本质与C#迭代器

协程并非Unity的专利,而是一种广泛存在于编程领域的控制流机制。在C#中,yield return关键字和IEnumerator接口构成了协程实现的基石。让我们先解剖一个最简单的协程示例:

IEnumerator SimpleCoroutine() { Console.WriteLine("步骤1执行"); yield return null; Console.WriteLine("步骤2执行"); yield return new WaitForSeconds(1.5f); Console.WriteLine("步骤3在1.5秒后执行"); }

这段代码揭示了协程的三个关键特征:

  • 分步执行:通过yield return将代码分割为多个可中断的执行块
  • 状态保持:每次恢复执行时能记住上次离开的位置
  • 异步等待:可以暂停指定时间或直到条件满足

在底层,C#编译器会将包含yield return的方法转换为一个状态机类。这个自动生成的类会:

  1. 维护当前执行位置(状态)
  2. 保存局部变量值
  3. 实现IEnumerator接口的MoveNext/Current成员

2. 构建简易协程调度器

要实现协程调度,我们需要模拟Unity中的MonoBehaviour核心功能。下面是一个最小化的协程调度器实现框架:

public class CoroutineScheduler { private List<IEnumerator> _runningCoroutines = new List<IEnumerator>(); public void StartCoroutine(IEnumerator coroutine) { _runningCoroutines.Add(coroutine); } public void Update() { for(int i = 0; i < _runningCoroutines.Count; ) { var coroutine = _runningCoroutines[i]; if(!coroutine.MoveNext()) { _runningCoroutines.RemoveAt(i); continue; } // 处理等待对象 if(coroutine.Current is IWaitCondition wait) { if(!wait.Check()) continue; } i++; } } }

关键组件说明:

组件职责实现要点
协程列表管理所有运行中的协程使用List<IEnumerator>存储
Update循环驱动协程执行每帧调用,遍历所有协程
MoveNext推进协程执行返回false表示协程结束
等待机制处理暂停条件通过IWaitCondition接口实现

3. 实现YieldInstruction等待机制

Unity提供了丰富的等待指令,如WaitForSecondsWaitUntil等。我们可以通过接口抽象来实现这些功能:

interface IWaitCondition { bool Check(); } class WaitForSeconds : IWaitCondition { private float _targetTime; public WaitForSeconds(float seconds) { _targetTime = Environment.TickCount + seconds * 1000; } public bool Check() => Environment.TickCount >= _targetTime; } class WaitUntil : IWaitCondition { private Func<bool> _predicate; public WaitUntil(Func<bool> predicate) { _predicate = predicate; } public bool Check() => _predicate(); }

使用示例:

IEnumerator TestCoroutine() { Console.WriteLine("等待2秒..."); yield return new WaitForSeconds(2); Console.WriteLine("等待结束"); bool condition = false; Console.WriteLine("等待条件满足..."); yield return new WaitUntil(() => condition); }

4. 状态机视角下的协程执行

让我们通过一个协程实例,观察状态机如何工作:

IEnumerator ComplexCoroutine() { int counter = 0; // 局部变量会被状态机保存 Console.WriteLine("阶段1"); yield return new WaitForSeconds(1); counter++; Console.WriteLine($"阶段2, counter={counter}"); yield return new WaitUntil(() => counter > 0); Console.WriteLine("阶段3"); }

编译器生成的状态机大致结构如下:

private sealed class <ComplexCoroutine>d__0 : IEnumerator<object> { // 状态字段 private int <>1__state; private object <>2__current; // 局部变量 private int counter; object IEnumerator.Current => <>2__current; bool MoveNext() { switch(<>1__state) { case 0: <>1__state = -1; counter = 0; Console.WriteLine("阶段1"); <>2__current = new WaitForSeconds(1); <>1__state = 1; return true; case 1: <>1__state = -1; counter++; Console.WriteLine($"阶段2, counter={counter}"); <>2__current = new WaitUntil(() => counter > 0); <>1__state = 2; return true; case 2: <>1__state = -1; Console.WriteLine("阶段3"); return false; } return false; } }

状态机的核心工作流程:

  1. 状态保存<>1__state记录当前执行位置
  2. 局部变量持久化:所有局部变量提升为类字段
  3. 控制流转:通过switch-case跳转到对应代码块
  4. 返回值处理:通过<>2__current返回等待对象

5. 高级协程控制功能

完整的协程系统还需要支持更丰富的控制功能。以下是几个关键扩展:

5.1 协程停止与嵌套

public class CoroutineHandle { public IEnumerator Coroutine { get; } public bool IsDone { get; private set; } public CoroutineHandle(IEnumerator coroutine) { Coroutine = coroutine; } public void Stop() { IsDone = true; } } public CoroutineHandle StartCoroutine(IEnumerator coroutine) { var handle = new CoroutineHandle(coroutine); _runningCoroutines.Add(new Wrapper(handle)); return handle; } private IEnumerator Wrapper(CoroutineHandle handle) { while(handle.Coroutine.MoveNext() && !handle.IsDone) { yield return handle.Coroutine.Current; } handle.IsDone = true; }

5.2 并行协程组

public IEnumerator WaitAll(params IEnumerator[] coroutines) { var handles = coroutines.Select(StartCoroutine).ToList(); while(handles.Any(h => !h.IsDone)) { yield return null; } } // 使用示例 yield return WaitAll( CoroutineA(), CoroutineB(), CoroutineC() );

5.3 异常处理机制

private IEnumerator SafeWrapper(IEnumerator coroutine) { while(true) { try { if(!coroutine.MoveNext()) break; } catch(Exception ex) { Console.WriteLine($"协程异常: {ex.Message}"); break; } yield return coroutine.Current; } }

6. 性能优化与实践建议

在实现协程系统时,需要注意以下性能关键点:

内存分配优化

  • 重用等待对象(对象池模式)
  • 避免每帧创建新的委托实例
  • 预分配协程列表容量

执行效率提升

// 快速路径优化示例 bool MoveNext() { if(<>1__state == 0) goto case0; if(<>1__state == 1) goto case1; return false; case0: // 初始状态逻辑 <>1__state = 1; return true; case1: // 后续状态逻辑 return false; }

最佳实践对比表

实践推荐做法不推荐做法
等待对象重用静态实例每帧new新对象
条件检查缓存委托实例每次创建新lambda
协程嵌套控制深度<3层深层嵌套调用
长时间运行分帧处理单帧完成所有工作

7. 实战:用自制协程系统实现游戏逻辑

让我们用自制的协程系统实现一个简单的敌人AI:

IEnumerator EnemyAI() { while(true) { // 巡逻阶段 yield return PatrolFor(5f); // 发现玩家后追击 yield return ChasePlayer(); // 攻击冷却 yield return new WaitForSeconds(2f); } } IEnumerator PatrolFor(float duration) { float startTime = Environment.TickCount; while(Environment.TickCount - startTime < duration * 1000) { // 实现巡逻移动逻辑 Console.WriteLine("巡逻中..."); yield return null; } } IEnumerator ChasePlayer() { bool playerInSight = true; while(playerInSight) { // 实现追击逻辑 Console.WriteLine("追击玩家!"); yield return null; // 模拟视野检查 playerInSight = new Random().Next(0, 10) > 2; } }

这个实现展示了如何用协程优雅地组织复杂的状态行为,相比传统状态机或回调方式,代码更加线性直观。

http://www.jsqmd.com/news/920997/

相关文章:

  • 云边端协同与智能算法:如何用代码重塑城市停车体验
  • AI钓鱼攻击:生成式AI如何重塑网络安全威胁与防御策略
  • [开源] API语义异常检测网关:面向医保与安全团队的实时请求风控系统,基于多维规则+时间序列建模识别薅羊毛与误操作
  • AHB总线SPLIT与RETRY响应机制详解
  • 80.EDL/Fastboot/Recovery/DFU模式深度剖析,读懂安卓iOS刷机核心机制
  • LiveNVR实战:将老旧海康摄像头通过ISUP协议接入,并转成GB28181对接上级平台
  • 数据组织:从数据仓库到数据网格,构建高效数据治理体系
  • 从剪刀石头布到德州扑克:后悔匹配算法原理与Python实现
  • 为线上Android设备开个“后门”:手把手教你给Android 11 User版本编译并集成su命令
  • 告别盲测:一份给5G射频测试工程师的SUL功率验证实操指南(基于38.521-1最新版)
  • 81.Fastboot/EDL协议底层详解,读懂GPT分区与payload固件加密逻辑
  • 构建PB级向量数据库:架构设计与工程实践全解析
  • T89C51CC01内部EEPROM操作与编程详解
  • 告别Mac不习惯!手把手教你用大白菜PE给苹果电脑装Win7双系统(保姆级图文)
  • Flutter VLC播放RTSP流媒体,这5个参数调优让你的延迟降到500ms以内
  • 82.高通EDL9008联发科BROM底层协议、供电时序、短路检测原理详解
  • Ubuntu 20.04上搞定Pylith 4.0.0和ParaView 5.12.0:一个地球物理学研究生的完整配置手记(含HDF5冲突终极解法)
  • AI集成实战:从数字化审计到工程落地的避坑指南
  • ARM Compiler 6.00 update 1版本解析与使用指南
  • 动态现金对冲策略:算法驱动的风险管理与资产配置实践
  • 别再傻傻分不清了!一文搞懂Unity编辑器扩展的四种绘制方式(EditorWindow/Editor/PropertyDrawer)
  • 从FAST天眼到游戏建模:圆柱面方程在三维空间中的‘降维’实战技巧
  • 告别硬编码!用ABAP函数VRM_SET_VALUES动态生成下拉列表(附完整代码)
  • ChatGPT辅助Python爬虫开发:从静态抓取到反爬策略实战
  • ROS2多机调试避坑指南:从虚拟机Ping通到节点真正通讯,我踩过的那些‘坑’
  • 人生感悟 --- 如何让一个人甘心服从你的领导
  • 从电赛作品到产品思维:聊聊单相逆变器并联系统中的那些‘坑’与优化思路
  • MTKClient救砖指南:3个关键场景下的联发科设备修复方案
  • 数据科学一日入门:从零到完整项目实战指南
  • 新手避坑指南:用Quartus Prime 21.1在FPGA上实现3-8译码器(附完整Verilog代码与仿真)