任务6:FrameTestComponent-组件事件系统练习

FrameTestComponent组件纯练习了解et组件与事件用,没实际用途。在Init中添加练习测试组件FrameTestComponent。

这个组件练习的目标是这样的:

  • 将组件扩展Update系统事件,做到持续调用组件定义的Update方法,每次count计数+1
  • 每间隔1秒调用一次
  • public int count = 1;
    public int waitTime = 1000;
    public bool interval  = false;

    应用TimerComponent 组件来实现每间隔1秒改变interval状态,实现组件的Update可以间隔1秒才会执行一次。

  • TimerComponent timerComponent = Game.Scene.GetComponent<TimerComponent>();
    await timerComponent.WaitAsync(waitTime);

    给组件加系统Update事件扩展类和扩展方法

  • [ObjectSystem]
        public class FrameTestComponentUpdateSystem : UpdateSystem<FrameTestComponent>
        {
            public override void Update(FrameTestComponent self)
            {
                self.Update();
            }
        }

    本组件实际的Update方法

  • public class FrameTestComponent: Component
        {
            public void Update()
            {
                if(interval){
                    //间隔时不调用UpdateAsync
                    return;
                }
                this.UpdateAsync().Coroutine();
            }

    在Init中添加今天的练习组件

    \Assets\Model\Init.cs

  • //练习2
    Game.Scene.AddComponent<FrameTestComponent>();

    创建完整的FrameTestComponent代码

    \Assets\Model\Test05\FrameTestComponent.cs

  • using System;
    using System.Collections.Generic;
    using Google.Protobuf;
    
    namespace ETModel
    {
        [ObjectSystem]
        public class FrameTestComponentUpdateSystem : UpdateSystem<FrameTestComponent>
        {
            public override void Update(FrameTestComponent self)
            {
                self.Update();
            }
        }
    
        public class FrameTestComponent: Component
        {
            public int count = 1;
            public int waitTime = 1000;
            public bool interval  = false;
            
            public void Update()
            {
                if(interval){
                    //间隔时不调用UpdateAsync
                    return;
                }
                this.UpdateAsync().Coroutine();
            }
            private async ETVoid UpdateAsync(){
                Log.Info($"===>frame{count}");
                
                //调用UpdateAsync时修改interval状态,计数+1
                interval = true;
                count++;
                
                //可每秒执行一次
                TimerComponent timerComponent = Game.Scene.GetComponent<TimerComponent>();
                await timerComponent.WaitAsync(waitTime);
                //间隔后修改interval状态
                interval = false;
            }
        }
    }

    在unity中运行,就可以观察实现效果。

    • 希望通过这样的小练习可以磨练自己尝试应用实体,组件,系统事件。
    • 大家自己也可以设想一些简单的目标,尝试用实体,组件,系统事件来实现。

    下一节我们再做一个更复杂点的组件练习。

posted @ 2023-01-27 17:08  Domefy  阅读(25)  评论(0)    收藏  举报