VContainer-optimization/async-container-build | 优化——异步容器构建

VContainer 在构建容器时会执行反射等预处理操作。
如果要减少主线程阻塞:

  1. LifetimeScope.autoRun 设置为 false
  2. 场景加载后手动调用 LifetimeScope.Build

例如:

var nextScene = await LoadSceneAsync(...);

var lifetimeScope = LifetimeScope.Find<MyLifetimeScope>(nextScene.Scene);

// 异步解决方案
await UniTask.Run(() => lifetimeScope.Build());

⚠️ Unity 依赖的功能 builder.RegisterComponentInHierarchy() 无法在后台线程中运行。

若报错可使用 Awake 替代。

例如:

class GameLifetimeScope : LifetimeScope
{
    Ground groundInScene;

    protected override void Awake()
    {
        // 在主线程中运行。
        groundInScene = FindObjectOfType<Ground>();

        base.Awake();
    }

    protected override void Configure(IContainerBuilder builder)
    {
        // 现在可以在后台线程中运行。
        builder.RegisterInstance(groundInScene);
    }
}
posted @ 2025-02-18 15:24  凌雪寒  阅读(53)  评论(0)    收藏  举报