Version: 2018.4
Universal Windows Platform: Association launching
Universal Windows Platform: WinRT API in C# scripts

Класс AppCallbacks

You could call it a bridge between your main application and Unity engine. Here, we’ll try to explain what every call to AppCallbacks exactly does. Let’s build solution and explore App.xaml.cs file, which gets created if you use .NET Scripting Backend.

sealed partial class App : Application
{
    private WinRTBridge.WinRTBridge _bridge;
    private AppCallbacks appCallbacks;
    public App()
    {
        this.InitializeComponent();
        appCallbacks = new AppCallbacks(false);
    }

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame == null)
        {
            var mainPage = new MainPage();
            Window.Current.Content = mainPage;
            Window.Current.Activate();

            _bridge = new WinRTBridge.WinRTBridge();
            appCallbacks.SetBridge(_bridge);

            appCallbacks.SetSwapChainBackgroundPanel(mainPage.GetSwapChainBackgroundPanel());

            appCallbacks.SetCoreWindowEvents(Window.Current.CoreWindow);

            appCallbacks.InitializeD3DXAML();
        }

        Window.Current.Activate();
    }
}

private WinRTBridge.WinRTBridge _bridge;

Сперва, что такое WinRTBridge. Он используется в недрах Unity для совершения некоторых native-to-managed, managed-to-native операций, он не предназначен для использования разработчиками. Из-за некоторых ограничений платформы WinRT, он не может быть создан из кода движка Unity, вот почему вместо этого WinRTBridge был создан здесь и передаётся движку Unity через appCallbacks.SetBridge(_bridge).

appCallbacks = new AppCallbacks(false);

Теперь давайте поближе рассмотрим класс AppCallbacks. Когда вы его создаёте, вы указываете, что ваша игра будет работать в другом потоке. Для обратной совместимости вы также можете указать, что ваше приложение может работать в потоке UI, но это делать не рекомендуется, т.к. существует ограничение от Microsoft - если ваше приложение не будет отвечать в течение первых 5 секунд, вы не сможете пройти WACK (Windows Application Certification), читайте подробнее здесь - http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184840(v=vs.105).aspx. Представьте, что ваш первый уровень довольно большой и требуется приличное количество времени для его загрузки, но т.к. ваше приложение работает в UI потоке, UI не будет отвечать до тех пор, пока ваш уровень полностью не загрузится. Вот почему рекомендуется всегда запускать вашу игру в другом потоке.

Дополнительная информация про UI поток доступна здесь - http://msdn.microsoft.com/en-us/library/windows/apps/hh994635.aspx

Note: Code located in App.xaml.cs, MainPage.xaml.cs is always running on UI thread, unless called from InvokeOnAppThread function.

appCallbacks.SetSwapChainBackgroundPanel(mainPage.GetSwapChainBackgroundPanel());

Эта строка просто передаёт XAML контрол в Unity, который будет использован для вывода рендера DirectX 11.

appCallbacks.SetCoreWindowEvents(Window.Current.CoreWindow);

Устанавливает основное окно для Unity, Unity подписывается на следующие события (их может быть больше, в зависимости от того, когда эта информация обновлена):

  • VisibilityChanged
  • Closed
  • PointerCursor
  • SizeChanged
  • Activated
  • CharacterReceived
  • PointerPressed
  • PointerReleased
  • PointerMoved
  • PointerCaptureLost
  • PointerWheelChanged
  • AcceleratorKeyActivated

appCallbacks.InitializeD3DXAML();

Это основной метод инициализации для Unity, он совершает следующие действия:

  • Parse command line arguments, set by AppCallbacks.AddCommandLineArg()
  • Инициализирует DirectX 11 устройство
  • Загружает первый уровень

На этой стадии, когда Unity закончит загрузку первого уровня, он войдёт в главный цикл.

Остальные методы

  • void InvokeOnAppThread(AppCallbackItem item, bool waitUntilDone)

Invokes a delegate on application thread, useful when you want to call your script function from UI thread.

  • void InvokeOnUIThread(AppCallbackItem item, bool waitUntilDone)

Invokes a delegate on UI thread, useful when you want to invoke something XAML specific API from your scripts.

  • bool RunningOnAppThread()

Returns true, if you’re currently running in application thread.

  • bool RunningOnUIThread()

Returns true, if you’re currently running in UI thread.

  • void InitializeD3DWindow()

Initialization function for D3D application.

  • void Run()

Function used by D3D application, for entering main loop.

  • bool IsInitialized()

Returns true, when first level is fully loaded.

  • void AddCommandLineArg(string arg)

Sets a command line argument for application, must be called before InitializeD3DWindow, InitializeD3DXAML.

  • void SetAppArguments(string arg) / string GetAppArguments()

Sets application arguments, which can be later accessed from Unity API - UnityEngine.WSA.Application.arguments.

  • void LoadGfxNativePlugin(string pluginFileName)

This function is obsolete and does nothing. In previous versions of Unity, this was needed to register native plugins for callbacks such as UnityRenderEvent. All plugins are now registered automatically. This function will be removed in a future update.

  • void ParseCommandLineArgsFromFiles(string fileName)

Parses command line arguments from a file, arguments must be separated by white spaces.

  • bool UnityPause(int pause)

Pauses Unity if you pass 1, unpauses if you pass 0, useful if you want to temporary freeze your game, for ex., when your game is snapped.

  • void UnitySetInput(bool enabled)

Enables/Disables input.

  • bool UnityGetInput()

Returns true, if Unity will process incoming input.

  • void SetKeyboardTriggerControl(Windows.UI.Xaml.Controls.Control ctrl)

Sets the control to be used for triggering on screen keyboard. This control will simply receive focus, when on screen keyboard is requested in scripts. Should be called with control, that does open keyboard on focus.

  • Windows.UI.Xaml.Controls.Control GetKeyboardTriggerControl()

Returns control, currently used control for triggering keyboard input. See SetKeyboardTriggerControl.

  • void SetCursor(Windows.UI.Core.CoreCursor cursor)

Sets system cursor. The given curosr is set for both CoreWindow and independent input source (if used).

  • void SetCustomCursor(unsigned int id)

Sets system cursor to custom. Parameter is cursor resource ID. Cursor is set for both CoreWindow and independent input source (if used).

Universal Windows Platform: Association launching
Universal Windows Platform: WinRT API in C# scripts