版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq826364410/article/details/82119588
最近需要开发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();
}
}
}