Unity 游戏框架搭建 (十五) 优雅的QChain (零)

来源:互联网 发布:windows temp环境变量 编辑:程序博客网 时间:2024/05/17 08:49

加班加了三个月终于喘了口气,博客很久没有更新了,这段期间框架加了很多Feature,大部分不太稳定,这些Feature中实现起来比较简单而且用的比较稳定的就是链式编程支持了。

什么是链式编程?

我想大家应该都接触过DOTween,用起来是这样的。
C#
transform.DOMove(Vector3.one, 0.5f)
.SetEase(Ease.InBack)
.OnKill(() => Debug.Log("on killed"))
.OnComplete(() => Debug.Log("on completed"));

像以上.XXX().YYY().ZZZ()这种写法就叫链式编程了。

QChain是什么?

QFramework中有零零散散支持了链式写法,打算整理出来作为一个独立的库进行过维护。目前的使用方式如下:
``` C#
this.Show()
.LocalIdentity() // 归一化
.LocalPosition(Vector3.back)
.LocalPositionX(1.0f)
.Sequence() // 开始序列
.Delay(1.0f)
.Event(() => Log.I("frame event"))
.Until(() => count == 2)
.Event(() => Log.I("count is 2"))
.Begin() // 执行序列
.DisposeWhen(() => count == 3)
.OnDisposed(() => Log.I("On Disposed"));

        this.Repeat()            .Delay(1.0f)            .Event(() => count++)            .Begin()            .DisposeWhenGameObjDestroyed();        this.Repeat(5)            .Event(() => Log.I(" Hello workd"))            .Begin()            .DisposeWhenFinished(); // 默认是这个        this.Sequence()            .Delay(1.0f)            .Event(() => Log.I("delay one second"))            .Delay(1.0f)            .Event(() => Log.E("delay two second"))            .Begin();
    #### 为什么要用QChain前段时间在给公司写一个蓝牙的插件,比较麻烦的是蓝牙管理类的状态同步和当状态改变时通知其他对象的问题。但是有了QChain,蓝牙连接的代码可以这样写:``` C#            this.Sequence()                .Event(() => PTBluetooth.Initialize(true, false))                .Until(() => PTBluetooth.IsInitialized)                .Until(() => PTBluetooth.IsOpened)                .Event(() => PTBluetooth.ScanPeripheral((address, name, rssi, adInfo) => name.Contains("device")))                .Until(() => PTBluetooth.ScannedDevices.Count >= 1)                .Event(() => PTBluetooth.ConnectToPeripheral(PTBluetooth.ScannedDevices[0].Address))                .Begin()                .DisposeWhen(()=>                {                    if (PTBluetooth.IsInitialized && !PTBluetooth.IsOpened)                    {                        // TODO: 这里处理初始化失败逻辑                        return true;                    }                                        // ... 其他失败逻辑处理                    return false;                });

这样写的好处是,逻辑不会分散到处都是。相比于协程,生命周期更好进行管理(不用管理协程对象),可作为协程的替代方案。还有其他的好处随着本系列的更新逐个讨论。

源码地址:

目前在写该文的时候,还没进行整理。Github也是在上一秒建好的- -,打算从最简单最容易实现的代码开始逐步整理到如下仓库里。
如果感兴趣参与维护,欢迎联系我。
GitHub - liangxiegame/QChain: Unity Chainning Support

相关链接:

  • QChain地址:https://github.com/liangxiegame/QChain
  • QFramework地址:https://github.com/liangxiegame/QFramework

转载请注明地址:凉鞋的笔记http://liangxiegame.com/

微信公众号:liangxiegame

#output/writing/Unity游戏框架搭建

阅读全文
0 0
原创粉丝点击