WebGL 构建选项允许 Unity 将内容发布为 JavaScript 程序,而这些程序可使用 HTML5/JavaScript、WebAssembly、WebGL 渲染 API 和其他 Web 标准在 Web 浏览器中运行 Unity 内容。要为 WebGL 构建和测试内容,请在 Build Player 窗口中选择 WebGL 构建目标,然后单击 Build & Run。
我们使用 emscripten 编译器工具链将 Unity 运行时代码(用 C和 C++ 编写)交叉编译为 WebAssembly(也称为 Wasm),这种格式的特点是文件体积小,加载时间短,内存效率高,并且执行速度接近原生执行速度。有关 Unity 中的 WebAssembly 的更多信息,请阅读这篇博客文章。
要将 .NET 游戏代码(C# 脚本)转换为 WebAssembly,我们使用一种称为 IL2CPP 的技术。IL2CPP 接受 .NET 字节码并将其转换为相应的 C++ 源文件,然后使用 emscripten 进行编译以将脚本转换为 Wasm。
桌面平台的大多数主要浏览器的当前版本都支持 Unity WebGL 内容,但不同浏览器提供的支持程度存在差异。Unity WebGL 不支持移动设备。
并非所有 Unity 功能都可用于 WebGL 构建,主要是由于平台的限制。具体而言:
由于 JavaScript 中缺少线程支持,因此不支持线程。在 Unity 内部使用线程来加速性能以及在脚本代码和托管的 dll 中使用线程都是不受支持的。实质上不支持 System.Threading
命名空间中的任何内容。
无法在 Visual Studio 中调试 WebGL 构建。请参阅:对 WebGL 构建进行调试和故障排除。
出于安全考虑,浏览器不允许直接访问 IP 套接字来进行联网。请参阅:WebGL 网络。
WebGL 图形 API 等效于 OpenGL ES 2.0 和 3.0,存在一些限制。请参阅:WebGL 图形。
WebGL 构建使用基于 Web 音频 API 的自定义音频后端。此情况下仅支持基本音频功能。请参阅:使用 WebGL 中的音频。
WebGL 是一个 AOT 平台,因此不允许使用 System.Reflection.Emit
来动态生成代码。在所有其他 IL2CPP 平台、iOS 和大多数游戏主机上都是如此。
2018–03–19 页面已修订
从 2018.1 开始,MonoDevelop 由 Visual Studio 取代
从 2018.2 开始,WebAssembly 取代了 asm.js
在 2019.1 中删除了 asm.js
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.