unity-webview

repository·master·Indexed 25 days ago

https://github.com/gree/unity-webview

A Unity plugin that overlays native WebView/WKWebView components over the Unity rendering view. It supports Android, iOS, Unity Web Player, Mac, and Windows (via Microsoft WebView2). The plugin allows for loading URLs and HTML, executing JavaScript, and communicating between JavaScript and Unity.

Tokens
10.1K
Snippets
9
Records
68
Agent score
81%

What's inside unity-webview

  1. Windows Platform Support Plan for Unity WebView

    master
    The Windows support implementation for unity-webview uses Microsoft WebView2 (Edge Chromium) as the backend. It follows an off-screen rendering pattern similar to the Mac implementation: a native C++ DLL handles the WebView2 instance, captures bitmaps via CapturePreview, and passes them to Unity to be rendered via OnGUI. This allows the WebView to be overlaid in Unity and enables JavaScript interoperability.
  2. Windows Platform Support Overview

    master
    The unity-webview plugin supports Windows (both Unity Editor and Standalone builds) by using Microsoft WebView2 (Edge Chromium) as the backend. The implementation follows an "offscreen render → composite in Unity" pattern, where a hidden native window captures a bitmap via CapturePreview, which is then rendered as a texture within Unity's OnGUI loop.
  3. Quickstart using the sample project

    master

    The easiest way to get started is by using the preconfigured sample project:

    1. Clone the repository.
    2. Open sample/Assets/Sample.unity in Unity. Accept any compatibility warnings.
    3. Import the package by double-clicking dist/unity-webview.unitypackage and clicking Import, or use the Package Manager.
    4. Select the SampleWebView GameObject in the hierarchy and enter your desired default URL.
    5. Select your target platform and build.
  4. Prevent Windows WebView2 crashes during Destroy

    master

    When using the Windows Editor or Standalone Windows builds, loading heavy web pages (especially those with hash navigation like https://www.interserv.com.tw/#service) can cause Unity to crash when pressing 'Stop'. This is due to a race condition where the WebView2 engine is destroyed while still in a busy/loading state.

    To mitigate this, you must ensure that navigation is stopped and the managed pointer is cleared before the native destruction process begins.

  5. Configure Android Permissions and Features

    master

    The Android implementation requires specific configurations depending on the features you use.

    File Input Fields

    If you need file input fields, ensure you have android.permission.READ_EXTERNAL_STORAGE, android.permission.WRITE_EXTERNAL_STORAGE, and android.permission.CAMERA permissions. If you do not need file input fields, use dist/unity-webview-nofragment.unitypackage to avoid using Android Fragments.

    Camera and Microphone Access

    To enable camera or microphone access via navigator.mediaDevices.getUserMedia, you must define specific script constants and call the corresponding runtime methods:

    1. Camera:
      • Define UNITYWEBVIEW_ANDROID_ENABLE_CAMERA.
      • Call webViewObject.SetCameraAccess(true); at runtime.
    2. Microphone:
      • Define UNITYWEBVIEW_ANDROID_ENABLE_MICROPHONE.
      • Call webViewObject.SetMicrophoneAccess(true); at runtime.

    Note: For Android API 23+, you must also request these permissions at runtime using UnityEngine.Android.Permission.

  6. Fix Windows WebView2 crash during Destroy

    master

    When using the Windows Editor or Standalone builds, loading heavy websites (e.g., those with extensive JS or hash-based navigation like https://www.interserv.com.tw/#service) can cause Unity to crash during the Destroy process. This is typically due to a race condition between the main thread and the STA thread when WebView2 is in a 'busy' or 'loading' state.

    To mitigate this, implement the following two core fixes:

    1. Stop navigation before releasing COM (C++)

    In plugins/Windows/WebViewPlugin.cpp, within the WM_WEBVIEW_DESTROY case, ensure you call Stop() on the webview instance before setting the controllers to nullptr. This allows WebView2 to cancel ongoing navigation and exit the busy state before the COM objects are released.

    2. Prevent race conditions in C# OnDestroy

    In the C# implementation (e.g., plugins/WebViewObject.cs), modify the OnDestroy logic for Windows platforms. You must nullify the webView pointer before calling the native destroy method. This prevents the Update loop from attempting to call GetMessage or Render on a pointer that is currently being destroyed in the native layer.

    Recommended Implementation Pattern:

    if (webView == IntPtr.Zero) return;
    var ptr = webView;
    webView = IntPtr.Zero;
    _CWebViewPlugin_Destroy(ptr);
  7. Configure Windows WebView2 Debug Logging

    master

    You can enable internal debug logs for the Windows plugin to troubleshoot mouse, keyboard, and windowing issues. The logs are output via OutputDebugString (labeled WV_LOG).

    To enable logging:

    1. Locate the WEBVIEW_DEBUG macro at the top of WebViewPlugin.cpp.
    2. Set it to 1.
    3. Rebuild the plugin.
    4. Use DebugView or the Visual Studio Output window to view the logs.
  8. Deploy Windows Native DLL to Unity

    master

    After building the C++ Win32 DLL (e.g., WebView.dll), place it in the following Unity directory structure:

    • 64-bit: Assets/Plugins/x86_64/WebView.dll
    • 32-bit (optional): Assets/Plugins/x86/WebView.dll

    Plugin Settings: Ensure the .meta file for the DLL is configured via the PluginImporter with the following settings:

    • Editor (Windows): Checked
    • Standalone (Windows / Win64): Checked
    • CPU: x86_64 (for 64-bit) or x86 (for 32-bit)
  9. Restore WebView2 SDK for Windows Plugin

    master

    The plugin requires WebView2 SDK headers and libraries. You must restore these before building the DLL. Choose one of the following three methods:

    Navigate to the plugins/Windows folder in PowerShell and run the provided script. This automatically handles nuget.exe and restores the required package.

    Method B: Manual NuGet Restore

    If you have the NuGet CLI installed, navigate to plugins/Windows and run the install command.

    Method C: Manual SDK Download

    1. Download the 1.0.3800.47 .nupkg file from NuGet: Microsoft.Web.WebView2.
    2. Rename the extension to .zip and extract it.
    3. Place the extracted build\native\include and build\native\x64 (or x86) in the appropriate paths, or update the WebViewPlugin.vcxproj include/library directories.
  10. Optimize Windows WebView2 Navigation and Texture Refreshing

    master

    When using unity-webview on Windows, the visual content is rendered via CapturePreview off-screen bitmaps. To prevent the Unity texture from getting stuck on old frames or failing to update during rapid navigation, follow these integration patterns:

    Prevent Texture Freezing

    If the WebView texture stops updating, it is often because the captureInProgress flag is stuck. Ensure that navigation completion events are correctly clearing this flag so that the next Unity Update cycle can schedule a new CapturePreview request.

    Handle Rapid URL Switching

    To avoid race conditions where a new Navigate call is ignored because a previous navigation hasn't finished stopping, implement a delayed navigation pattern:

    1. Stop the current navigation.
    2. Clear the capture/refresh flags.
    3. Delay the new Navigate call to the next message loop (e.g., using PostMessage instead of immediate execution).

    Configure Refresh Rate

    On Windows, the WebViewObject uses a bitmapRefreshCycle to control how often the off-screen texture is captured.

    • Default value: 10 (recommended for performance).
    • High-frequency updates: If the visual updates feel sluggish, you can manually lower this value (e.g., to 3) to increase the redraw frequency, though this will increase CPU/GPU usage.
  11. Windows Plugin Deployment and Placement

    master

    When deploying the Windows plugin, place the compiled DLLs in the following Unity directory structure:

    • 64-bit: Assets/Plugins/x86_64/WebView.dll
    • 32-bit: Assets/Plugins/x86/WebView.dll

    Ensure the .meta files for these DLLs are configured using the PluginImporter to enable only the appropriate platforms: Editor (Windows) and Standalone (Windows / Win64).