Unity Web 构建中的 Javascript 接口
了解可在 Javascript 接口中使用的一些有用函数。
阅读时间4 分钟最后更新于 6 天前
Unity Web 构建中的 Javascript 接口提供了可用于配置 Web Applications 的有用函数和变量。您可以在 Javascript 库代码(.jslib 文件)中调用这些函数。
显示报错、Warning或自定义义横幅
使用 函数可显示 message 横幅,或重载该函数以自定义横幅以用于您自己的目的。
unityShowBanner()参数 | 描述 |
|---|---|
| 要显示的message。 |
| 要显示的 message 类型。例如:
|
默认 WebGL 模板中的以下代码设置报错和Warning横幅的外观。在自定义定义模板中,可以重载此函数来创建自己的横幅类型,或自定义非关键警告和报错消息的显示方式。
function unityShowBanner(msg, type) { var warningBanner = document.querySelector("#unity-warning"); function updateBannerVisibility() { warningBanner.style.display = warningBanner.children.length ? 'block' : 'none'; } var div = document.createElement('div'); div.innerHTML = msg; warningBanner.appendChild(div); if (type == 'error') div.style = 'background: red; padding:10px;'; else { if (type == 'warning') div.style = 'background: yellow; padding:10px;'; setTimeout(function() { warningBanner.removeChild(div); updateBannerVisibility(); "25270591" } updateBannerVisibility(); }
您可以在 .jslib 文件中调用 函数。以下横幅永久显示要显示的 message 作为报错 message:
unityShowBanner('The message you want to show', 'error');
Change WebGL 上下Attributes
使用 可自定义用于初始化 WebGL 上下文的创建 Attributes。只能Change以下Attributes:
webglContextAttributespowerPreferencepremultipliedAlphapreserveDrawingBuffer
这些选项仅在使用 WebGL 渲染 API WhenApply。如果使用 WebGPU 渲染 API,则会忽略 Field。
webglContextAttributes要Change这些Attributes,请在自定义 WebGL 模板中Change配置Object。例如:
script.onload = () => { config['webglContextAttributes'] = { powerPreference:'性能 premultipliedAlpha: false, preserveDrawingBuffer:true、 }; createUnityInstance(画布、配置、(progress) => {
powerPreference选项 | 描述 |
|---|---|
| 默认 | 让用户 Agent 决定哪种 GPU 配置最适合。这是默认值。 |
| 性能 | 将渲染性性能于功耗之上。 |
| low-power | 将节电优先于渲染性性能。 |
有关每个属性的更多信息,请参阅 Mozilla ON HTMLCanvasElement: getContext() 的文档。
有关 Unity WebGL 图形的信息,请参阅 WebGL 图形。
将Projectreaming Assets
如果需要将 Streaming Assets ON 不同的 CDN,可以调整 配置Object 的 属性以指向 Streaming Assets 所在的完整网址。
createUnityInstance()streamingAssetsUrlvar buildUrl = "Build";var config = { dataUrl: buildUrl + "/{{{ DATA_FILENAME }}}", frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}", codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}",#if MEMORY_FILENAME memoryUrl: buildUrl + "/{{{ MEMORY_FILENAME }}}",#endif#if SYMBOLS_FILENAME symbolsUrl: buildUrl + "/{{{ SYMBOLS_FILENAME }}}",#endif streamingAssetsUrl:"https://mygameserver.com/StreamingAssets/", // 添加此行以重载默认的 Streaming Assets 位置 companyName: "{{{ COMPANY_NAME }}}", productName:"{{ PRODUCT_NAME }}", productVersion:"{{{ PRODUCT_VERSION }}",};
Control 网页缓存
使用 函数来控制在中缓存的 URL。函数接受网址作为参数并返回 、 或 。还可以重载该函数以实现自己的目的。
cacheControl()UnityCachemust-revalidateimmutableno-store有关代码示例和更多信息,请参阅 Web 缓存行为。