Skip to content
简体中文

Mount Godot UI ​

Create the host ​

Add GodotUiRoot to the scene tree on the engine thread. Create UiService with the host's IGameDispatcher, and register routes and native view factories in UiRegistry. Share one pause manager with the UI if you use pause menus.

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));
}

Use RegisterGodotScene<TControl, TArgs> to bind data to a typed PackedScene root. In the quick start, root.PageScene is an exported scene reference and the callback receives a QuickStartPage.

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

You can also infer both types from a callback such as (QuickStartPage page, int args, UiViewContext context) => …. The one-type-parameter overload still accepts an optional binder that receives a Control.

The factory checks the root type each time it instantiates the scene. It runs the callback while the root is detached and frees the new node if the type check or binding fails. Use _Ready or IGodotUiLifecycle.OpenAsync for work that requires a mounted node. After binding, leave the node detached so the UI service can mount and dispose it.

Build views from regular Control scenes. Pages receive arguments and actions and can close themselves through UiViewContext. A dialog uses its context to complete a typed result.

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());
    }
}

View lifecycle ​

Implement IGodotUiLifecycle to prepare state in OpenAsync and release application subscriptions in CloseAsync. The view is mounted and hidden when it opens. Its lease handles node cleanup.

Subscribe while a typed page is open ​

Install GeWuYou.GFramework.Godot in a Godot .NET project. In the host described above, use a PackedScene with a ScorePage root. Keep the page's event producer on the Godot thread, or dispatch its updates to that thread before touching a Control.

See ScorePage script.

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}");
    }
}

In the composition root, register that scene as scoreScene. Create the host's UiService with this registry, mounted root, and dispatcher. The binding callback only stores the typed data. The mounted page subscribes during OpenAsync and owns the returned IDisposable. Both the service's CloseAsync callback and the node's _ExitTree release it safely, even when both run.

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));

Run at least two open, update, and close cycles with the same route and event. Check the initial argument and the display after each update. Await ui.CloseAsync(handle), check that the listener count returns to zero, and trigger another event to confirm the closed page receives no update. Run these scenarios in the native smoke example.

  • Navigating back from the page has the same cleanup boundary as closing the handle. Pushing another page can hide this one while retaining it in history. Its open-lifetime subscription stays active until it actually closes.
  • With the page open, have the host await ui.StopAsync() before removing the mount root or quitting. The listener count returns to zero. In a separate disposable run, removing the mount subtree directly should also drop the listener via _ExitTree. Use the service to manage navigation and shutdown so its state and the scene tree stay aligned.

Use GodotUiInputBridge to dispatch semantic actions from Godot. Await UI shutdown before removing the mount root. See the integration tutorial for the full interaction.

Apache License 2.0