我為 Unity 內置的移動應用程式構建了一些自定義 UI 縮放功能,以補償各種手機螢屏比例。我還想防止螢屏尺寸變化,隨著可折疊手機的興起,我認為這是一種風險。
我實施的初步解決方案是將腳本附加到必須調整大小的物件上,結構如下:
public class ScreenElementSizer : MonoBehaviour {
private int screenWidth_1 = Screen.width;
private int screenHeight_1 = Screen.height;
// Start is called before the first frame update
void Start() {
ScreenResized();
}
// Resizing functions here
private void ScreenResized() {
}
// On every screen refresh
void Update()
{
if ((Screen.width != screenWidth_1) || (Screen.height != screenHeight_1)) {
ScreenResized();
screenWidth_1 = Screen.width;
screenHeight_1 = Screen.height;
}
}
正如您所看到的,這是一個非常簡單的解決方案,我將先前樣本的Screen.width和存盤Screen.height在變數 ( screenWidth_1& screenHeight_1) 中,然后在每個樣本上比較它們(更新),如果有差異(螢屏更改),則觸發調整器腳本。
它當然作業正常。我認為這是非常標準的編碼邏輯。if為每個樣本的每個物件運行一個/兩個這樣的額外陳述句可能并不昂貴。
我剛接觸 Unity,想知道是否有更好的、內置的或更有效的方法來完成這項任務。
明確地說,我知道基于寬度和高度縮放的內置畫布調整器工具。我特別指的是當螢屏尺寸發生變化時,您想應用一些基于腳本的特殊大小調整邏輯的情況。
感謝您的任何想法。
uj5u.com熱心網友回復:
沒有內置事件,但您可以創建自己的事件。
DeviceChange.cs -
using System;
using System.Collections;
using UnityEngine;
public class DeviceChange : MonoBehaviour
{
public static event Action<Vector2> OnResolutionChange;
public static event Action<DeviceOrientation> OnOrientationChange;
public static float CheckDelay = 0.5f; // How long to wait until we check again.
static Vector2 resolution; // Current Resolution
static DeviceOrientation orientation; // Current Device Orientation
static bool isAlive = true; // Keep this script running?
void Start() {
StartCoroutine(CheckForChange());
}
IEnumerator CheckForChange(){
resolution = new Vector2(Screen.width, Screen.height);
orientation = Input.deviceOrientation;
while (isAlive) {
// Check for a Resolution Change
if (resolution.x != Screen.width || resolution.y != Screen.height ) {
resolution = new Vector2(Screen.width, Screen.height);
if (OnResolutionChange != null) OnResolutionChange(resolution);
}
// Check for an Orientation Change
switch (Input.deviceOrientation) {
case DeviceOrientation.Unknown: // Ignore
case DeviceOrientation.FaceUp: // Ignore
case DeviceOrientation.FaceDown: // Ignore
break;
default:
if (orientation != Input.deviceOrientation) {
orientation = Input.deviceOrientation;
if (OnOrientationChange != null) OnOrientationChange(orientation);
}
break;
}
yield return new WaitForSeconds(CheckDelay);
}
}
void OnDestroy(){
isAlive = false;
}
}
執行 -
DeviceChange.OnOrientationChange = MyOrientationChangeCode;
DeviceChange.OnResolutionChange = MyResolutionChangeCode;
DeviceChange.OnResolutionChange = MyOtherResolutionChangeCode;
void MyOrientationChangeCode(DeviceOrientation orientation)
{
}
void MyResolutionChangeCode(Vector2 resolution)
{
}
信用 - 道格麥克法蘭
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340627.html
標籤:统一3d 用户界面 调整大小 调整窗口大小 自动调整大小
上一篇:統一垂直布局組高度不計算兒童
