Unity调用Windows弹出确认框,任意拖动窗口,保持16:9固定宽高比

发表于2018-09-18
评论0 3.3k浏览
做PC端的游戏,就需要做一些对应版本的游戏需求,比如说Unity调用Windows弹出确认框,任意拖动窗口,保持16:9固定宽高比等。整理了各个需求的代码,分享给有需要的小伙伴们。

首先,创建一个弹出框的类
using System;
using System.Runtime.InteropServices;
/// <summary>
/// 调用Window的弹框
/// </summary>
public class Message
{
    [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern int MessageBox(IntPtr handle, string message, string title, int type);
}

然后,具体的功能类
using UnityEngine;
using System;
public class WindowMod1 : MonoBehaviour
{
    private float aspect16_9;
    private int screenWidth = 1280;
    private int screenHeight = 720;
    private int widthScal = 16;
    private int heightScal = 9;
    void Start()
    {
        //16:9固定比例
        aspect16_9 = (float)widthScal / heightScal;
    }
    void Update()
    {
        SetResolution();
    }
    void SetResolution()
    {
        int curScreenWidth = Screen.width;
        int curScreenHeight = Screen.height;
        if(curScreenWidth == screenWidth && curScreenHeight == screenHeight)
        {
            return;
        }
        float curScale = (float)curScreenWidth / curScreenHeight;
        if (curScale > aspect16_9)
        {
            int h = (int)((heightScal * curScreenWidth) / widthScal);
            Screen.SetResolution(curScreenWidth, h, false);
            screenWidth = curScreenWidth;
        }
        else if (curScale < aspect16_9)
        {
            int w = (int)((widthScal * curScreenHeight) / heightScal);
            Screen.SetResolution(w, curScreenHeight, false);
            screenHeight = curScreenHeight;
        }
    }
    void OnApplicationQuit()
    {
        Application.CancelQuit();
        int returnNum = Message.MessageBox(IntPtr.Zero, "确定退出游戏吗?", "我的游戏", 1);
        if(returnNum == 1)
        {
            //点击确定按钮
            Application.Quit();
        }
    }
}
来自:https://blog.csdn.net/qq826364410/article/details/82119588

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引