Async all,一切基于异步。

始于Main

Main脚本继承Monobehaviour,设计为单例,是程序入口。提供如下功能:

  • Mono事件回调。Awake、Update、LateUpdate、FixedUdpate、OnGUI等等Monobehaviour事件。
  • 协程管理。统一管理协程,支持一个key多个协程。

本框架绝大多数的类都不继承Mono脚本,但不反对继承Mono脚本。

起于IStartup

通过IStartup,将框架层与游戏逻辑层解耦。

// 框架入口,挂在初始游戏场景上
public sealed partial class Main : MonoSingleton<Main>
{
    private readonly static ThreadSynchronizationContext s_ThreadSynchronizationContext
        = new(Thread.CurrentThread.ManagedThreadId);

    private IServiceLocator m_Locator = new DefaultServiceLocator();

    protected override async void Awake()
    {
        base.Awake();

        DontDestroyOnLoad(gameObject);

        SynchronizationContext.SetSynchronizationContext(s_ThreadSynchronizationContext);

        var startup = GetComponent<IStartup>();
        try
        {
            await startup.StartAsync();

            Log.INFO("Main", $"<color=green>MGF initialized.</color>");
        }
        catch (Exception e)
        {
            Log.ERROR("Main", e);
        }
    }

    // ...
}
// 自定义启动脚本
public sealed class GameAppStart : IStartup
{
    public override async UniTask StartAsync()
    {
        // 1. 组件注册
        // profiler显示组件
        Main.Instance.gameObject.AddComponent<Saro.Profiler.ProfilerDisplay>();

        // 事件组件
        FGame.Register<EventComponent>();

        // 资源组件
        FGame.Register<XAssetComponent>().Initialize();

        // 音效组件
        await FGame.Register<SoundComponent>().InitializeAsync(FGame.Resolve<XAssetComponent>(), "Assets/Res/Audios/");

        // UI组件
        await FGame.Register<UIComponent>().InitializeAsync(FGame.Resolve<XAssetComponent>(), "Assets/Res/Prefab/UI/");

        // ....

        // 2. 启动游戏逻辑
        // 打开游戏主UI
        await UIComponent.Current.OpenUIAsync<UIStartPanel>();
    }

    // ...
}