Lucia的宝藏之地
首页项目归档照片墙音乐说说杂谈友链关于
封面

Unity Windos端电脑屏幕窗口适配

2026-08-16 14:43:15
# unity
# 经验记录

问题描述

由于各个电脑显示器分辨率不同,导致了游戏画面在不同显示器上显示效果不同,可能导致UI错位或者画面显示不全

可添加以下脚本和设置来解决此问题

代码

using UnityEngine;

public class WindowManager : MonoBehaviour
{
    public static WindowManager Instance;

    // 9:16
    private const float TargetAspect = 9f / 16f;

    // 给电脑屏幕预留的边距
    private const int ScreenMargin = 80;

    private void Awake()
    {
        // 防止切换场景后重复创建
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;

        // 跨场景保留
        DontDestroyOnLoad(gameObject);
    }

    private void Start()
    {
        SetWindowSize();
    }

    private void SetWindowSize()
    {
        // 获取电脑当前分辨率
        int screenWidth = Screen.currentResolution.width;
        int screenHeight = Screen.currentResolution.height;

        // 最大可用尺寸
        int maxWidth = screenWidth - ScreenMargin;
        int maxHeight = screenHeight - ScreenMargin;

        // 先按照高度计算
        int windowHeight = maxHeight;
        int windowWidth = Mathf.RoundToInt(windowHeight * TargetAspect);

        // 如果宽度超过屏幕,则按照宽度重新计算
        if (windowWidth > maxWidth)
        {
            windowWidth = maxWidth;
            windowHeight = Mathf.RoundToInt(windowWidth / TargetAspect);
        }

        // 设置为窗口模式
        Screen.SetResolution(
            windowWidth,
            windowHeight,
            FullScreenMode.Windowed
        );

        Debug.Log(
            $"游戏窗口设置为:{windowWidth} × {windowHeight}"
        );
    }
}

设置


‍

avatar

Lucia

你好,我是 Lucia。 一名热衷于 AI 与创意编程的开发者, 学过设计,喜欢构建拥有氛围感与交互感的数字产品。 目前专注于: Agent Workflow、生成式 AI 与游戏设计。 这里记录我的代码、灵感与深夜实验。

2026年8月

一
二
三
四
五
六
日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Recent Records

电脑实用工具分享——ScreenToGif Gif录屏软件

2026-05-24 22:20:18

电脑实用工具分享——Everything 文件快速查询

2026-05-24 22:15:52

Unity内置AI对话

2026-05-13 22:37:54