美文网首页
unity+puerts转微信小游戏踩坑记录

unity+puerts转微信小游戏踩坑记录

作者: taiyosen | 来源:发表于2023-04-12 20:07 被阅读0次

    TypeError: video.canPlayType is not a function

    image.png
    原因是游戏里使用了VideoPlayer,然而小游戏虽然支持视频播放能力,但暂无法直接使用VideoPlayer。
    参见:小游戏是否支持Unity VideoPlayer
    解决方案:https://github.com/wechat-miniprogram/minigame-unity-webgl-transform/tree/main/Demo/WX_Video

    某些AB包加载失败

    原因竟然是美术制作的部分图片后缀名部分包含了两个..,比如abc..png,正常的Android/PC等都没问题,但小游戏会报404,重命名即可。

    企业微信截图_16801639077548.png

    ios真机报错:Invalid regular expression: invalid group specifier name

    开发者工具模拟器可以正常运行,Android机也可以,但ios机器报错,意思是非法的正则表达式,见
    https://developers.weixin.qq.com/community/develop/doc/000e6cb25b49284c9a094417256c00?highLine=Invalid%2520regular%2520expression
    其实就是诸如(?<=)(?<!)(?=)(?!)这些正则表达式ios不支持~

    unity input无法输入

    需要做输入法适配:https://github.com/wechat-miniprogram/minigame-unity-webgl-transform/blob/main/Design/InputAdaptation.md

    开启profilingFuncs和ProfilingMemory后导出webgl工程失败

    stderr:INFO:root:generating system library: dlmalloc_tracing.bc... (this will be cached in "C:\Program Files\Unity2019.4.18f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten_FastComp_Win\cache\asmjs\dlmalloc_tracing.bc" for subsequent builds)
    Traceback (most recent call last):  File "C:\Program Files\Unity2019.4.18f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 3063, in <module>    sys.exit(run())  File "C:\Program Files\Unity2019.4.18f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 1632, in run    extra_files_to_link += system_libs.calculate([f for _, f in sorted(temp_files)] + extra_files_to_link, in_temp, stdout_=None, stderr_=None, forced=forced_stdlibs)  File "C:\Program Files\Unity2019.4.18f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\system_libs.py", line 618, in calculate    libfile = shared.Cache.get(name, do_create, extension=suffix)  File "C:\Program Files\Unity2019.4.18f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\cache.py", line 103, in get    shutil.copyfile(temp, cachename)  File "C:\Program Files\Unity2019.4.18f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\lib\shutil.py", line 83, in copyfile    with open(dst, 'wb') as fdst:IOError: [Errno 13] Permission denied: 'C:\\Program Files\\Unity2019.4.18f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\Emscripten_FastComp_Win\\cache\\asmjs\\dlmalloc_tracing.bc'[WEBGL]Exception: Failed building WebGL Player.
    

    我使用的是2019.4.18f1,估计是版本问题,考虑更换版本:
    https://github.com/wechat-miniprogram/minigame-unity-webgl-transform/blob/main/Design/UnityVersion.md

    InvalidOperationException: The build target does not support build appending.

    原先使用2019.4.18f1时,导出webgl工程是没问题的,改用2021.3.16f1后,导出webgl工程会报错:

    InvalidOperationException: The build target does not support build appending.
      at UnityEditor.BuildPipeline.BuildPlayer (System.String[] scenes, System.String locationPathName, System.String assetBundleManifestPath, UnityEditor.BuildTargetGroup buildTargetGroup, UnityEditor.BuildTarget target, System.Int32 subtarget, UnityEditor.BuildOptions options, System.String[] extraScriptingDefines) [0x00068] in <11d97693183d4a6bb35c29ae7882c66b>:0 
      at UnityEditor.BuildPipeline.BuildPlayer (UnityEditor.BuildPlayerOptions buildPlayerOptions) [0x00039] in <11d97693183d4a6bb35c29ae7882c66b>:0 
      at UnityEditor.BuildPipeline.BuildPlayer (System.String[] levels, System.String locationPathName, UnityEditor.BuildTarget target, UnityEditor.BuildOptions options) [0x0004b] in <11d97693183d4a6bb35c29ae7882c66b>:0 
      at BuildCommand.BuildForWebGL () [0x00022] in F:\games\MuWebGL_Develop\project\Assets\Editor\Builder\BuildCommand.cs:182 
    

    报错大意是:指定的编译目标(这里是BuildTarget.WebGL)不支持增量编译
    查到一篇类似的贴子:https://forum.unity.com/threads/resolved-using-acceptexternalmodificationstoplayer-to-append-to-macos-xcode-project.1230933/
    查到unity的文档:https://docs.unity3d.com/2019.4/Documentation/ScriptReference/BuildPipeline.BuildCanBeAppended.html
    导出webgl工程时,直接去掉BuildOptions.AcceptExternalModificationsToPlayer,或者使用下述代码判断:

    if (BuildPipeline.BuildCanBeAppended(target, location) == CanAppendBuild.Yes)
    {                
           ops |= BuildOptions.AcceptExternalModificationsToPlayer;
    }
    

    BINARYEN_TRAP_MODE 问题

    emcc2: error: Invalid command line option -s BINARYEN_TRAP_MODE=clamp: The wasm backend does not support a trap mode (it always clamps, in effect)[WEBGL]BuildFailedException: Incremental Player build failed!
    

    之前打webgl后,运行时会出现float溢出的问题,于是添加了下述代码

    // 2019.4.18f1需使用下述编译参数解决float越界问题
    PlayerSettings.WebGL.emscriptenArgs = "-s \"BINARYEN_TRAP_MODE='clamp'\"";
    

    unity升到2021后导出webgl工程会报上述报错,意思是这个命令行选项不支持,wasm实际上一直都回clamps,所以修改为

    #if !UNITY_2021_3_OR_NEWER
            // 2019.4.18f1需使用下述编译参数解决float越界问题
            PlayerSettings.WebGL.emscriptenArgs = "-s \"BINARYEN_TRAP_MODE='clamp'\"";
    #endif
    

    Error: listen EADDRINUSE: address already in use :::54998

    20:44:57:815 [WEBGL][websockify wrapper] Proxying from :54998 to localhost:34999
    
    20:44:57:825 [WEBGL][websockify wrapper] [ERROR] events.js:292
    20:44:57:826 [WEBGL]
    [websockify wrapper] [ERROR]       throw er; // Unhandled 'error' event
    [websockify wrapper] [ERROR]       ^
    [websockify wrapper] [ERROR] Error: listen EADDRINUSE: address already in use :::54998
    [websockify wrapper] [ERROR]     at Server.setupListenHandle [as _listen2] (net.js:1313:16)
    [websockify wrapper] [ERROR]     at listenInCluster (net.js:1361:12)
    [websockify wrapper] [ERROR]     at Server.listen (net.js:1447:7)
    [websockify wrapper] [ERROR]     at new WebSocketServer (F:\Program Files\2021.3.16f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\websockify\node_modules\ws\lib\websocket-server.js:97:20)
    20:44:57:826 [WEBGL]
    [websockify wrapper] [ERROR]     at Object.<anonymous> (F:\Program Files\2021.3.16f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\websockify\websockify.js:178:12)
    [websockify wrapper] [ERROR]     at Module._compile (internal/modules/cjs/loader.js:1138:30)
    [websockify wrapper] [ERROR]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    [websockify wrapper] [ERROR]     at Module.load (internal/modules/cjs/loader.js:986:32)
    20:44:57:826 [WEBGL]
    [websockify wrapper] [ERROR]     at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    [websockify wrapper] [ERROR]     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    20:44:57:826 [WEBGL]
    [websockify wrapper] [ERROR] Emitted 'error' event on WebSocketServer instance at:
    
    20:44:57:826 [WEBGL][websockify wrapper] [ERROR]     at Server.emit (events.js:315:20)
    20:44:57:826 [WEBGL]
    [websockify wrapper] [ERROR]     at emitErrorNT (net.js:1340:8)
    [websockify wrapper] [ERROR]     at processTicksAndRejections (internal/process/task_queues.js:84:21) {
    20:44:57:826 [WEBGL]
    [websockify wrapper] [ERROR]   code: 'EADDRINUSE',
    
    20:44:57:826 [WEBGL][websockify wrapper] [ERROR]   errno: 'EADDRINUSE',
    [websockify wrapper] [ERROR]   syscall: 'listen',
    
    20:44:57:826 [WEBGL][websockify wrapper] [ERROR]   address: '::',
    [websockify wrapper] [ERROR]   port: 54998
    20:44:57:826 [WEBGL]
    [websockify wrapper] [ERROR] }
    

    用netstat查看哪个进程占用了端口,最好发现是unity 2019的nodejs,应该是之前用2019打过webgl,unity就会启用一个nodejs服务,现在用unity 2021打,同样会启用一个nodejs服务,于是报错。解决办法就是直接把正在运行的那个nodejs进程kill掉。

    gzip设置

    如果设置了压缩格式为gzip,那么http服务器需添加Content-Encoding:gzip,否则要勾选fallback。因为此前一直使用tomcat做的http服务器,结果没法简便地配置在response添加Content-Encoding:gzip,需要自定义Filter,也太麻烦了,索性再加一个nginx服务器,配置可以参考unity文档:
    https://docs.unity3d.com/cn/current/Manual/webgl-server-configuration-code-samples.html

    GameGlobal is not defined

    ception thrown: ReferenceError: GameGlobal is not defined,ReferenceError: GameGlobal is not defined
        at _glClear (http://192.168.8.27/mu_develop/browser/Build/export_browser.framework.js.gz:3:367029)
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[11848]:0x36cf3b
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[74712]:0x18a3f42
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[74838]:0x18b616f
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[73716]:0x1866056
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[32066]:0xacf253
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[32066]:0xacf2c4
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[28659]:0xa1e352
        at http://192.168.8.27/mu_develop/browser/Build/export_browser.wasm.gz:wasm-function[40051]:0xd6e25b
        at browserIterationFunc (http://192.168.8.27/mu_develop/browser/Build/export_browser.framework.js.gz:3:340077)
        at callUserCallback (http://192.168.8.27/mu_develop/browser/Build/export_browser.framework.js.gz:3:293275)
        at Object.runIter (http://192.168.8.27/mu_develop/browser/Build/export_browser.framework.js.gz:3:294535)
        at Browser_mainLoop_runner (http://192.168.8.27/mu_develop/browser/Build/export_browser.framework.js.gz:3:292810)
    p
    

    之前打webgl后是可以在浏览器里跑的,后来安装了微信小游戏插件后,再打就会报上述的错误,这个GameGlobal是微信模拟浏览器的Windows用的,解决办法:

    使用微信的模板,比如Assets\WebGLTemplates\WXTemplate2020\index.html,里面会定义GameGlobal

    Incremental build failed

    emcc2: error: '"F:/Program Files/2021.3.16f1/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/node/node.exe" "F:\Program Files\2021.3.16f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten\src\compiler.js" C:\Users\CLIENT~1\AppData\Local\Temp\tmp4dbxf8g0.txt' failed (1)
    *** Tundra build failed (41.65 seconds), 8 items updated, 635 evaluated
    [WEBGL]Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js: undefined symbol: _ZN6il2cpp2os6Thread16HasCurrentThreadEv (referenced by top-level compiled C/C++ code)[WEBGL]Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js: Aborting compilation due to previous errors[WEBGL]Building Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js failed with output:
    emcc2: error: '"F:/Program Files/2021.3.16f1/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/node/node.exe" "F:\Program Files\2021.3.16f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten\src\compiler.js" C:\Users\CLIENT~1\AppData\Local\Temp\tmp4dbxf8g0.txt' failed (1)[WEBGL]BuildFailedException: Incremental Player build failed!
    

    论坛上有人遇到相同的问题:
    https://forum.unity.com/threads/build-fails-with-undefined-symbol-_zn6il2cpp2os6thread16hascurrentthreadev.1359299/
    我使用的是Unity 2021.3.16f1,经过测试,BuildOptions.Development并不会导致构建失败,导致失败的是BuildOptions.AllowDebuggingBuildOptions.ConnectWithProfiler

    PlayerSettings.WebGL.threadsSupport导致报错

    System.ArgumentException: You're trying to copy to F:/games/MuWebGL_Develop/export_browser/Build/export_browser.framework.js more than once. Previously from Library/Bee/artifacts/WebGL/build/debug_WebGL_wasm/build.framework.js and now from Library/Bee/artifacts/WebGL/build/debug_WebGL_wasm/build.worker.framework.js
       at Program.Main(String[] args)[WEBGL]BuildFailedException: Incremental Player build failed!
    

    我用的2021.3.16f1,一开PlayerSettings.WebGL.threadsSupport就报错

    Webgl Task相关问题

    https://forum.unity.com/threads/async-await-and-webgl-builds.472994/
    方案:https://github.com/Cysharp/UniTask

    dlopen

    https://emscripten.org/docs/compiling/Dynamic-Linking.html

    webp

    可以使用这个插件,在webgl下支持webp:
    https://github.com/netpyoung/unity.webp
    构建的时候可能会报

    Assets\unity.webp\Runtime\NativeLibwebpdemux.cs(112,17): error CS0103: The name 'Unsafe' does not exist in the current context
    Assets\unity.webp\Runtime\NativeLibwebpdemux.cs(141,17): error CS0103: The name 'Unsafe' does not exist in the current context
    Assets\unity.webp\Runtime\NativeLibwebpdemux.cs(112,17): error CS0103: The name 'Unsafe' does not exist in the current context
    Assets\unity.webp\Runtime\NativeLibwebpdemux.cs(141,17): error CS0103: The name 'Unsafe' does not exist in the current context
    

    大部分情况下是因为你直接通过.package安装,缺少了System.Runtime.CompilerServices.Unsafe.dll,建议通过UMP安装,修改Packages/manifest.json:

    {
      "dependencies": {
        "com.netpyoung.webp": "https://github.com/netpyoung/unity.webp.git?path=unity_project/Assets/unity.webp#0.3.9",
        "org.nuget.system.runtime.compilerservices.unsafe": "6.0.0"
      },
      "scopedRegistries": [
        {
          "name": "Unity NuGet",
          "url": "https://unitynuget-registry.azurewebsites.net",
          "scopes": [
            "org.nuget"
          ]
        }
      ]
    }
    

    但是你可能会遇到这个报错

    PrecompiledAssemblyException: Multiple precompiled assemblies with the same name System.Runtime.CompilerServices.Unsafe.dll included or the current platform. Only one assembly with the same name is allowed per platform. Assembly paths: 
    Assets/WX-WASM-SDK/Editor/TextureEditor/Release/System.Runtime.CompilerServices.Unsafe.dll
    D:/works/qj2d/webgl/project/Library/PackageCache/org.nuget.system.runtime.compilerservices.unsafe@6.0.0/System.Runtime.CompilerServices.Unsafe.dll
    UnityEditor.Scripting.ScriptCompilation.EditorBuildRules.ValidateAndGetNameToPrecompiledAssembly (UnityEditor.Scripting.ScriptCompilation.PrecompiledAssembly[] precompiledAssemblies) (at <afa5b9a1793446ff98b741dc036c4c6e>:0)
    UnityEditor.Scripting.ScriptCompilation.EditorBuildRules.ToScriptAssemblies (System.Collections.Generic.IDictionary`2[TKey,TValue] targetAssemblies, UnityEditor.Scripting.ScriptCompilation.ScriptAssemblySettings settings, UnityEditor.Scripting.ScriptCompilation.EditorBuildRules+CompilationAssemblies assemblies, System.Collections.Generic.HashSet`1[T] runUpdaterAssemblies) (at <afa5b9a1793446ff98b741dc036c4c6e>:0)
    

    因为微信插件里也用到了System.Runtime.CompilerServices.Unsafe.dll。这个问题本质上是微信小游戏插件依赖不规范,直接就把第三方插件放进文件夹里,这样就很容易和其他第三方插件冲突,我遇到的情况是,WX-WASM-SDK使用的是4.0.1,而uni.webp用的是6.0.0。最终解决办法:

    1. 不要通过UMP安装unity.webp,直接用.unitypackage安装
    2. System.Runtime.CompilerServices.Unsafe.dll复制到unity.webp/Runtime

    多线程

    unity webgl对多线程支持很有限...不支持C#的多线程,只支持c++级别的,参考
    https://docs.unity3d.com/ScriptReference/PlayerSettings.WebGL-threadsSupport.html
    有个方案,没亲试:
    https://medium.com/medialesson/so-you-want-to-use-multithreading-in-unity-webgl-5953769dd337

    关闭提示

    https://answers.unity.com/questions/1210601/webgl-build-callback-on-tab-close-or-browser-quit.html

    相关文章

      网友评论

          本文标题:unity+puerts转微信小游戏踩坑记录

          本文链接:https://www.haomeiwen.com/subject/lxgfddtx.html