在Canvas上挂以下代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScreenAudoChange : MonoBehaviour
{
private CanvasScaler canvas;
private float screen,rescreen;
private Vector2 oldscreen;
// Start is called before the first frame update
void Start()
{
canvas = gameObject.GetComponent<CanvasScaler>();
canvas.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvas.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
screen = canvas.referenceResolution.x / canvas.referenceResolution.y;
rescreen = (float)Screen.width / Screen.height;
Adaptive();
}
// Update is called once per frame
void Update()
{
if (oldscreen.x != Screen.width || oldscreen.y != Screen.height)
{
Adaptive();
}
}
void Adaptive()
{
rescreen = (float)Screen.width / Screen.height;
if (rescreen > screen)
{
canvas.matchWidthOrHeight = 1;
}
else
{
canvas.matchWidthOrHeight = 0;
}
oldscreen = new Vector2(Screen.width, Screen.height);
}
}