WeChat Mini Game Tuanjie Engine Adapter SDK

repository·main·Indexed 41 days ago

https://github.com/wechat-miniprogram/minigame-tuanjie-transform-sdk

An SDK providing integration support for Unity and Tuanjie Engine games to run as WeChat Mini Games. It enables WeChat-specific runtime capabilities, including mobile keyboard interfaces, touch event registration, and canvas rendering, via the GameGlobal.WXWASMSDK object. Version 0.1.1.

Tokens
16.5K
Snippets
72
Records
84
Agent score
50%

What's inside WeChat Mini Game Tuanjie Transform SDK

  1. Install the Unity/Tuanjie Engine SDK via Package Manager

    main

    To install the SDK in your Unity or Tuanjie Engine project, use the Unity Package Manager to add the repository via its Git URL.

    1. Open your project in Unity or Tuanjie Engine.
    2. Navigate to Window -> Package Manager in the menu bar.
    3. Click the + button in the top-right corner.
    4. Select Add package from git URL....
    5. Enter the repository Git URL: https://github.com/wechat-miniprogram/minigame-tuanjie-transform-sdk.git.
    https://github.com/wechat-miniprogram/minigame-tuanjie-transform-sdk.git
  2. Use the WeChat SDK mobile keyboard interface

    main

    The mobileKeyboard module provides a bridge between Unity/Tuanjie Engine and the WeChat Mini Game mobile keyboard. It allows you to show, hide, and manage text input via the native mobile keyboard.

    Key capabilities include:

    • Showing the keyboard with specific configurations (multiline, character limits, etc.).
    • Retrieving the current text value and selection.
    • Setting or updating the text currently in the keyboard.
    • Managing keyboard visibility and status.
    import mobileKeyboard from './path/to/mobileKeyboard/index.js';
    
    // Example: Showing the keyboard
    mobileKeyboard._JS_MobileKeyboard_Show(
      textPtr,      // Pointer to UTF8 string
      type,         // keyboardType
      true,         // autocorrection
      false,        // multiline
      false,        // secure
      false,        // alert
      placeholderPtr, 
      140,          // characterLimit
      frameworkData // data object containing string conversion helpers
    );
  3. Access the WeChat Unity SDK via GameGlobal.WXWASMSDK

    main

    The complete WeChat SDK surface is aggregated into a single object and attached to the global GameGlobal.WXWASMSDK namespace. This object provides access to a wide range of WeChat Mini Game capabilities, including:

    • User & Social: userInfo, share, gameClub, authorize, chat
    • Storage & Filesystem: storage, fs (File System)
    • Media: audio, video, videoDecoder, texture, camera, recorder, gameRecorder, font
    • Networking: TCPSocket, UDPSocket, uploadFile, cloud
    • Hardware & Input: bluetooth, gyroscope, touch, mobileKeyboard
    • Game Services: ad (Ads), openData, sdk (Core SDK)
    • Utilities: util, logger, canvasContext, canvasHelper
  4. Access the WXWASMSDK global object

    main

    The SDK provides a unified interface for Unity/Tuanjie engine integration within WeChat Mini Games. All core functionalities are aggregated into the GameGlobal.WXWASMSDK object. This includes modules for:

    • Canvas & Rendering: canvasHelper, canvasContext, texture
    • File System: fs
    • Audio & Video: audio, video, videoDecoder
    • Input: touch, mobileKeyboard
    • Utilities: util, logger, sdk
    • Special Callbacks: specialCallbacks

    Additionally, GameGlobal.unityNamespace.unityVersion is available to check the current Unity version.

  5. Use the Unity SDK video interface

    main

    The Unity SDK provides a JavaScript interface for managing video playback within WeChat Mini Games. This interface allows you to create video instances, control playback (play, pause, seek, loop), manage audio tracks, and update WebGL textures with video frames.

    Note that the API uses a handle-based system where most functions take a video ID (returned by _JS_Video_Create) as their first argument.

    // Example conceptual usage:
    // const videoId = _JS_Video_Create('https://example.com/video.mp4');
    // _JS_Video_Play(videoId, false);
    // _JS_Video_Seek(videoId, 10.5);
  6. Use the Unity SDK mobile keyboard interface

    main

    The mobileKeyboard module provides a JavaScript interface for controlling the WeChat Mini Game mobile keyboard from within a Unity/Tuanjie engine environment. It wraps wx.showKeyboard and related WeChat APIs to allow the engine to manage text input, character limits, and keyboard visibility.

    Key Capabilities

    • Show Keyboard: Display the keyboard with specific configurations like multiline support, character limits, and placeholder text.
    • Text Management: Retrieve the current text content or set new text values.
    • Visibility Control: Programmatically hide the keyboard.
    • Status Monitoring: Check if the keyboard is currently visible or has been dismissed.

    Note: This module relies on FrameworkData (passed during _JS_MobileKeyboard_Show) to handle string conversions between JavaScript and the engine's memory (UTF8/HEAP32).

    // Example conceptual usage via the exported interface
    import mobileKeyboard from './mobileKeyboard/index.js';
    
    // Show the keyboard
    mobileKeyboard._JS_MobileKeyboard_Show(
        textPtr,      // Pointer to UTF8 string
        type,         // keyboardType
        true,         // autocorrection
        false,        // multiline
        false,        // secure
        false,        // alert
        placeholder,  // placeholder
        140,          // characterLimit
        frameworkData // The engine's FrameworkData object
    );
    
    // Get the current text
    const textLen = mobileKeyboard._JS_MobileKeyboard_GetText(buffer, bufferSize);
    
    // Hide the keyboard
    mobileKeyboard._JS_MobileKeyboard_Hide(true); // true for delayed hide
  7. Use the WeChat SDK Gyroscope API in Unity

    main

    The gyroscope interface allows you to control the device's gyroscope sensor within a Unity/Tuanjie engine project running on WeChat Mini Games. It provides methods to start/stop the sensor and register callbacks for sensor changes and operation results (success/fail/complete).

    // Note: These functions are exported by the SDK and intended to be called from the Unity/C# side via the bridge.
    
    // 1. Register callbacks to handle asynchronous results
    WX_RegisterStartGyroscopeCallback(startCallback);
    WX_RegisterStopGyroscopeCallback(stopCallback);
    WX_RegisterOnGyroscopeChangeCallback(changeCallback);
    
    // 2. Start the gyroscope
    WX_StartGyroscope(id, { interval: 100 });
    
    // 3. Listen for sensor changes
    WX_OnGyroscopeChange();
    
    // 4. Stop the gyroscope
    WX_StopGyroscope(id, {});
    
    // 5. Unsubscribe from changes
    WX_OffGyroscopeChange();
  8. Register touch event callbacks in Unity SDK

    main

    To handle touch input within the Unity/Tuanjie engine environment, you must first register a callback function using the WX_RegisterOnTouch...Callback methods. These callbacks are invoked via WebAssembly (Wasm) using a pointer to the touch data.

    Once a callback is registered, you must enable the event listeners using the WX_OnTouch... methods to start receiving events from the WeChat Mini Game environment.

    import touchSDK from './path/to/touch/index.js';
    
    // 1. Register the callback that will receive the data pointer
    touchSDK.WX_RegisterOnTouchStartCallback((dataPtr, touchesCount, changedTouchesCount) => {
        // Handle touch data via the pointer in your C#/Wasm layer
        console.log('Touch started');
    });
    
    // 2. Enable the WeChat event listener
    touchSDK.WX_OnTouchStart();
  9. Troubleshoot WeChat Developer Tools errors after export

    main

    If your game project exports successfully but throws errors when running in the WeChat Developer Tools, it is likely because the WeChat Runtime package was pruned during the Tuanjie Engine export process.

    This happens when the game project is empty or the game code never invokes any runtime capabilities of the WXSDK. To resolve this, ensure you call at least one WXSDK capability within your game code to prevent the engine from stripping the runtime package during export.

  10. Configure the WeChat Minigame project via project.config.json

    main

    The project.config.json file is the primary configuration file for the WeChat Minigame project. It defines the project type, app ID, simulator settings, and various compilation and packaging behaviors. For Unity/Tuanjie engine projects using this SDK, ensure compileType is set to game and libVersion is specified to match your target environment.

    {
      "description": "项目配置文件",
      "setting": {
        "es6": true,
        "enhance": true,
        "minified": true,
        "useMultiFrameRuntime": true
      },
      "compileType": "game",
      "libVersion": "3.5.1",
      "appid": "$APP_ID",
      "projectname": "$PROJECT_NAME",
      "simulatorType": "wechat"
    }
  11. Configure the WeChat Miniprogram project settings

    main

    The project.config.json file defines the environment and compilation behavior for the WeChat Miniprogram game project. Key settings include:

    • compileType: Set to game for minigame projects.
    • libVersion: Specifies the WeChat SDK version to use (e.g., latest).
    • appid: The unique identifier for your WeChat Mini Program.
    • projectname: The name of your project.
    • simulatorType: The type of simulator to use (e.g., wechat).

    Commonly used setting flags:

    • es6: Enables ES6 features.
    • enhance: Enables enhanced compilation.
    • postcss: Enables PostCSS support.
    • minified: Enables code minification.
    • useMultiFrameRuntime: Enables multi-frame runtime support.
    • useIsolateContext: Enables isolated context.
    • useCompilerModule: Enables compiler modules.
    • uploadWithSourceMap: Enables uploading source maps during deployment.
    {
      "compileType": "game",
      "libVersion": "latest",
      "appid": "$APP_ID",
      "projectname": "$PROJECT_NAME",
      "simulatorType": "wechat",
      "setting": {
        "es6": true,
        "enhance": true,
        "minified": true,
        "useMultiFrameRuntime": true,
        "uploadWithSourceMap": true
      }
    }