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.效果展示

相关推荐
山河木马4 天前
矩阵专题1-怎么创建模型矩阵(uModelMatrix)
javascript·webgl·计算机图形学
山河木马5 天前
矩阵专题0-webGL中的矩阵
javascript·webgl·计算机图形学
一颗烂土豆10 天前
Meshopt 压缩深度解析,为什么它比 Draco 更快
前端·javascript·webgl
数据知道19 天前
视觉伪装(下):WebGL 渲染器与厂商特征的底层伪造与屏蔽
javascript·数据采集·webgl·指纹浏览器
niconicoC19 天前
让 Three.js 场景更真实:我用高斯泼溅和 SparkJS 做了一个可交互的 3D Demo
前端·webgl
sinat_3845031120 天前
【无标题】
unity·webgl
山河木马25 天前
无框架-原生webGL渲染-底层入门-1
前端·javascript·webgl
拾忆丶夜1 个月前
unity webgl 阴影条纹问题
unity·游戏引擎·webgl
GISer_Jing1 个月前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
GISer_Jing1 个月前
WebGL|Three.js渲染管线核心技术解析
java·javascript·webgl