WebGL平台动态修改窗口大小

1.静态设置

发布之前在Player Setting/Resolution and Presentation设置

2.动态设置

经过测试在WebGL平台打包后,Screen.SetResolution设置分辨率是不生效的

需要写js脚本

1.新建脚本WebGLResize.jslib,放在Plugins\WebGL下面

javascript 复制代码
mergeInto(LibraryManager.library, {
    ResetCanvasSize: function(width, height) {
        // 获取Unity canvas元素
        var canvas = document.querySelector("#unity-canvas");
        if (!canvas) {
            console.warn("无法找到Unity canvas元素");
            return;
        }
        
        // 设置canvas的新尺寸
        canvas.style.width = width + "px";
        canvas.style.height = height + "px";
        
        // 如果存在Unity实例,通知其resize
        if (Module) {
            Module.canvas.width = width;
            Module.canvas.height = height;
            
            // 触发Unity内部的resize事件
            if (typeof Module.onResize === 'function') {
                Module.onResize(width, height);
            }
        }
        
        // 调整容器大小(如果有父容器)
        var parent = canvas.parentElement;
        if (parent) {
            parent.style.width = width + "px";
            parent.style.height = height + "px";
        }
        
        console.log("画布已调整为: " + width + "x" + height);
    }
});

2.C#调用

完整代码:

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using TMPro;
using UnityEngine;

public class WebTest : MonoBehaviour
{
    public TextMeshProUGUI logText;

    public void Set600_960()
    {
        SetCustomCanvasSize(600, 960);
    }

    public void Set960_600()
    {
        SetCustomCanvasSize(960, 600);
    }

    public void ClearLog()
    {
        logText.text = "";
    }


#if UNITY_WEBGL && !UNITY_EDITOR
        [DllImport("__Internal")]
        private static extern void ResetCanvasSize(int width, int height);
#endif
// 设置自定义分辨率
    private void SetCustomCanvasSize(int width, int height)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
            ResetCanvasSize(width, height);
#endif
        string msg = $"{width}x{height}  Screen:{Screen.width}x{Screen.height}";
        AppendLogText(msg);
        Debug.LogWarning(msg);
    }

    void AppendLogText(string msg)
    {
        logText.text = logText.text + "\n" + msg;
    }
}

3.效果展示

相关推荐
UWA1 天前
GPM 2.0 WebGL 监测能力扩容|覆盖 Unity/Cocos/LayaAir 多引擎微信 & 抖音小游戏
unity·微信·性能优化·小游戏·webgl
像我这样帅的人丶你还1 天前
🚀苹果的液态玻璃咋做?🚀
前端·webgl·three.js
用户83134859306982 天前
Cesium实现动态流动火烧云晚霞效果(可用slider调整火烧云浓度)
vue.js·webgl·cesium
IT爱学堂2 天前
Three.js可视化企业实战WEBGL课,2023年全新WEB 3D THREEJS技术
前端·javascript·webgl
智商偏低3 天前
attribute 与 uniform 本质区别(WebGL)
webgl
进哥AI研习社4 天前
WebGL 与视频背景——首屏视觉层的性能博弈
性能优化·webgl·gpu·canvas·shader·帧率·视频背景
IT小白杨11 天前
链上任务与海外社媒多账号:环境隔离工具技术横评
经验分享·webgl·chrome devtools·安全架构·指纹浏览器
AI_AGENT_DEV_AI17 天前
数字孪生项目的开发
webgl
supermapsupport18 天前
SuperMap GIS 基础产品 FAQ 集锦(20260807)
webgl·supermap·idesktopx
supermapsupport18 天前
SuperMap iClient3D for WebGL 如何开启实体对象深度检测
webgl