Skip to content
English

挂载 Godot UI ​

创建宿主 ​

在引擎线程上将 GodotUiRoot 添加到场景树。通过同一个 IGameDispatcher 创建 UiService,将路由和原生视图工厂登记到 UiRegistry。需要暂停菜单时传入同一个暂停管理器。

csharp
// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0

using System.Threading;
using System.Threading.Tasks;
using GFramework.Core.Abstractions.Architectures;
using GFramework.Core.Architectures;
using GFramework.Game.Abstractions.Runtime;
using GFramework.Game.Abstractions.UI;
using GFramework.Game.Runtime;
using GFramework.Game.UI;
using GFramework.Godot.UI;
using Microsoft.Extensions.DependencyInjection;

namespace GodotIntegration.GettingStarted;

/// <summary>Composes ordinary services, explicitly ordered startup and the borrowed native host.</summary>
/// <remarks>All container access stays here. Native attachment follows resource validation; detachment follows UI stop.</remarks>
/// <param name="root">The borrowed scene and resource owner.</param>
/// <param name="dispatcher">The owning Godot thread.</param>
internal sealed class QuickStartArchitecture(QuickStartRoot root, IGameDispatcher dispatcher) : Architecture, IAsyncArchitectureHost
{
    /// <summary>Describes dependencies and startup participants before any service is activated.</summary>
    protected override void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(root);
        services.AddSingleton(dispatcher);
        services.AddComponent<QuickStartResources>(order: -100);
        services.AddSingleton(provider => CreateRoutes(provider.GetRequiredService<QuickStartResources>()));
        services.AddModule(new GameRuntimeModule(dispatcher, runtime =>
        {
            runtime.AddSingleton<IUiService>(provider => new UiService(provider.GetRequiredService<UiRegistry>(),
                root.UiRoot, dispatcher));
        }));
    }

    private UiRegistry CreateRoutes(QuickStartResources resources)
    {
        var routes = new UiRegistry();
        routes.RegisterGodotScene<QuickStartPage, int>(QuickStartRoot.PageRoute, root.PageScene, (page, _, _) =>
            page.Configure(resources.Get("welcome"), root.RequestConfirmation));
        routes.RegisterGodotDialog(QuickStartRoot.ConfirmRoute, (question, context) =>
        {
            var node = root.ConfirmScene.Instantiate();
            try
            {
                var confirm = (QuickStartConfirm)node;
                confirm.Configure(question, context, root.RunResponse);
                return confirm;
            }
            catch
            {
                node.Free();
                throw;
            }
        });
        return routes;
    }

    /// <inheritdoc />
    ValueTask IAsyncArchitectureHost.StartHostAsync(CancellationToken cancellationToken) =>
        new(dispatcher.InvokeAsync(() => root.AttachUiAsync(Services.GetRequiredService<IUiService>()), cancellationToken));

    /// <inheritdoc />
    protected override ValueTask OnStoppingAsync() => new(dispatcher.InvokeAsync(root.StopActionsAsync));

    /// <inheritdoc />
    protected override ValueTask OnStoppedAsync() => new(dispatcher.InvokeAsync(root.DetachUiAsync));
}

用 RegisterGodotScene<TControl, TArgs> 指定 PackedScene 的根节点类型并绑定数据。快速入门示例中的 root.PageScene 是导出的场景引用,回调接收 QuickStartPage 并配置页面。

csharp
routes.RegisterGodotScene<QuickStartPage, int>(QuickStartRoot.PageRoute, root.PageScene, (page, _, _) =>
    page.Configure(resources.Get("welcome"), root.RequestConfirmation));

也可在回调中显式标注参数类型,由编译器推断泛型,例如 (QuickStartPage page, int args, UiViewContext context) => …。只有一个泛型参数的重载仍支持可选的绑定回调,回调接收 Control。

工厂每次实例化场景时都会检查根节点的类型,并在节点进入场景树前执行绑定。类型不匹配或绑定抛出异常时,工厂会释放新实例。需要访问已挂载节点时,用 _Ready 或 IGodotUiLifecycle.OpenAsync。绑定成功后保持节点未挂载,由 UI 服务挂载和销毁。

使用普通 Control 场景制作视图。页面接收参数和动作,通过 UiViewContext 关闭自己。对话框用其上下文完成带类型的结果。

csharp
// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0

using System;
using System.Threading.Tasks;
using GFramework.Game.Abstractions.UI;
using Godot;

namespace GodotIntegration.GettingStarted;

/// <summary>Completes its typed result through a host-observed response that can run while the opener waits.</summary>
public partial class QuickStartConfirm : CenterContainer
{
    private string _question = string.Empty;
    private UiDialogContext<bool> _context = null!;
    private Action<Func<Task>> _run = null!;

    /// <summary>Receives the dialog's own completion context before entering the tree.</summary>
    /// <param name="question">Opening argument.</param>
    /// <param name="context">The owning UI instance.</param>
    /// <param name="run">Observed response admission.</param>
    public void Configure(string question, UiDialogContext<bool> context, Action<Func<Task>> run)
    {
        _question = question;
        _context = context;
        _run = run;
    }

    /// <inheritdoc />
    public override void _Ready()
    {
        GetNode<Label>("Panel/Content/Question").Text = _question;
        GetNode<Button>("Panel/Content/Accept").Pressed += () => _run(() => _context.CompleteAsync(result: true));
        GetNode<Button>("Panel/Content/Cancel").Pressed += () => _run(() => _context.CloseAsync());
    }
}

视图生命周期 ​

需要业务订阅时,实现 IGodotUiLifecycle,在 OpenAsync 准备状态,在 CloseAsync 解除订阅。打开时视图处于已挂载、隐藏状态。节点由视图租约释放。

管理强类型页面打开期间的订阅 ​

在 Godot .NET 工程中安装 GeWuYou.GFramework.Godot。沿用上面的宿主,使用一个以 ScorePage 为根节点的 PackedScene。让页面的事件生产者在 Godot 线程上工作,或先把更新分发到该线程再操作 Control。

参考 ScorePage 脚本。

csharp
// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0

using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using GFramework.Core.Events;
using GFramework.Godot.UI;
using Godot;

namespace GodotIntegration.GettingStarted;

/// <summary>Owns the score subscription only for the lifetime of this view.</summary>
public partial class ScorePage : Label, IGodotUiLifecycle
{
    private Event<int>? _scoreChanged;
    private int _initialScore;
    private IDisposable? _subscription;

    /// <summary>Stores dependencies while the route root is still detached.</summary>
    /// <param name="scoreChanged">Event owned by the host.</param>
    /// <param name="initialScore">Initial score supplied by the route.</param>
    public void Configure(Event<int> scoreChanged, int initialScore)
    {
        _scoreChanged = scoreChanged;
        _initialScore = initialScore;
    }

    /// <inheritdoc />
    public Task OpenAsync(CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ShowScore(_initialScore);
        _subscription ??= (_scoreChanged ?? throw new InvalidOperationException("Missing route binding."))
            .Register(ShowScore);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task CloseAsync(CancellationToken cancellationToken = default)
    {
        ReleaseSubscription();
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public override void _ExitTree() => ReleaseSubscription();

    private void ReleaseSubscription()
    {
        var subscription = _subscription;
        _subscription = null;
        subscription?.Dispose();
    }

    private void ShowScore(int score)
    {
        Text = string.Create(CultureInfo.InvariantCulture, $"Score: {score}");
    }
}

在装配入口将这个场景作为 scoreScene 登记。使用该 registry、已挂载的根节点和 dispatcher 创建宿主的 UiService。绑定回调只保存强类型数据。页面挂载后在 OpenAsync 中订阅并持有返回的 IDisposable。服务调用 CloseAsync、节点触发 _ExitTree 时都释放订阅,先后执行也安全。

csharp
var scoreChanged = new Event<int>();
var scoreRoute = new UiRoute<int>("score");
var routes = new UiRegistry();
routes.RegisterGodotScene<ScorePage, int>(scoreRoute, scoreScene,
    (page, score, _) => page.Configure(scoreChanged, score));

使用同一个路由和事件实例连续打开、更新、关闭至少两轮。打开后检查初始参数和每次更新后的页面内容,等待 ui.CloseAsync(handle) 后检查监听数为零,并再次触发事件确认页面不再收到更新。可在原生冒烟示例中运行这些场景。

  • 从该页面返回和关闭句柄都会执行同样的清理。推入另一个页面可能仅隐藏旧页面并保留历史,原页面在真正关闭前仍持有打开期间的订阅。
  • 页面打开时,让宿主先等待 ui.StopAsync(),再移除挂载根节点或退出,监听者数量恢复为零。另启一次临时运行,直接移除挂载子树,也应通过 _ExitTree 释放监听。日常导航和关闭宿主通过服务完成,确保服务状态与场景树一致。

将 Godot 动作交给 GodotUiInputBridge 做语义分发。在宿主退出时先等待 UI 停止,再移除挂载根。完整操作见Godot 接入教程。

Apache 2.0 许可证