Unity3d C#使用Screen.SetResolution设置无效的问题(问题在于Screen.width、Screen.height)

问题

在最近的Unity3d项目开发的过程中需要程序动态的修改分辨率的情况,于是使用Screen.SetResolution函数进行了设置,发现只有第一次生效的情况,测试设置代码如下:

    // Update is called once per frame
    void Update()
    {
    
    
        if (Input.GetKeyUp(KeyCode.T))
        {
    
    
            Screen.SetResolution(Screen.width, Screen.height, true);
        }
        else if (Input.GetKeyUp(KeyCode.R))
        {
    
    
            Screen.SetResolution(Screen.width, Screen.width / 16 * 9 > Screen.height ? Screen.height : Screen.width / 16 * 9, true);
        }
}

这个需求是一个竖屏的屏幕,需要全屏的显示和竖屏的显示之间切换。
竖屏全屏显示:
在这里插入图片描述

竖屏中横屏显示:
在这里插入图片描述
我的显示器作为竖屏,设置如图:
在这里插入图片描述

问题就是第一次切换正常,之后的调用就不正常。

解决方式

经过一番网上查找,还是没有,试过如LateUpdate函数中调用的方式,都是还是不行的。
直到我自己在各个函数值中打了Log:

void Update()
    {
    
    
        if (Input.GetKeyUp(KeyCode.T))
        {
    
    
            Debug.LogError("还原比例....Screen.width:" + Screen.width + "  Screen.height:" + Screen.height);
            Screen.SetResolution(Screen.width, Screen.height, true);
            Debug.LogError("还原比例完成..Screen.width:" + Screen.width + "  Screen.height:" + Screen.height);
        }
        else if (Input.GetKeyUp(KeyCode.R))
        {
    
    
            Debug.LogError("设置比例....Screen.width:" + Screen.width + "  Screen.height:" + Screen.height);
            Screen.SetResolution(Screen.width, Screen.width / 16 * 9 > Screen.height ? Screen.height : Screen.width / 16 * 9, true);
            Debug.LogError("设置比例完成..Screen.width:" + Screen.width + "  Screen.height:" + Screen.height);
        }
    }

日志如图:

在这里插入图片描述

可以发现第一次修改后的某个时机(不是Screen.SetResolution函数调用后立马)Screen.height 和Screen.width的值就会变成SetResolution设置的参数,所以之后依据Screen.height 和Screen.width来进行变更是的值是不会变化的,所以才造成的设置无效的假象。
我这里是指指定了 宽度2160和高度3840(4K的竖屏),在根据16:9的比例计算解决了该问题,而不能根据当前Screen.height 和Screen.width来计算比例或者进行设置,因为这两个值不是显示器的当前分辨率而是该程序运行的分辨率。

其它事项

在Unity3d出包的程序中调用Screen.SetResolution设置了程序的运行分辨率,再次启动如果不设置程序运行分辨率,程序将会以上次设置的运行分辨率下运行。
如上图的日志中,最后运行分辨率为 1080603,这时关闭程序,下次运行,如果没有代码设置Screen.SetResolution,程序的默认运行分辨率是1080603,Screen.width 和Screen.height值也是1080和603。

猜你喜欢

转载自blog.csdn.net/qq_33789001/article/details/126524179