針對大螢幕和折疊式裝置最佳化 Unity 遊戲

1. 簡介

在本程式碼研究室中,您將瞭解如何針對大螢幕和摺疊式裝置,最佳化 Unity Android 遊戲。您將使用 Lost Crypt 範例專案,實作顯示比例支援功能、擴大全螢幕使用率,以及回應摺疊狀態。

必要條件

  • 對 Unity 和 Android 開發作業有基本瞭解。
  • 大螢幕 Android 裝置,例如平板電腦或摺疊式手機。

課程內容

  • 如何實作支援各種顯示比例的功能。
  • 瞭解如何在遊戲的 UI 和攝影機設定中使用錨點,自動調整畫面大小。
  • 如何使用 Android 的 Jetpack Window Manager 偵測裝置的摺疊型態,並調整版面配置。

需求條件

  • Unity Hub 和編輯器:已安裝 Unity 2020 LTS 或 Unity 2022,並支援 Android 建構。
  • 硬體:大螢幕 Android 裝置,例如平板電腦或摺疊式手機。
  • 如果您打算使用技能,請使用代理式開發平台,例如 Google Antigravity。

2. Agent Skill

您也可以使用代理程式技能評估 Unity 遊戲專案。這項技能可協助您新增大小調整功能,並支援大螢幕和摺疊式裝置。詳情請參閱:GitHub

如何使用這項技能:

  1. 將 SKILL.md 檔案複製到代理目錄。如要進一步瞭解如何新增技能,請參閱「開始使用 Google Antigravity」。
  2. 在代理式 IDE (例如 Antigravity) 中,向代理提出有關大螢幕、折疊式裝置或大小調整的問題。
  3. 請代理人新增大螢幕和折疊式裝置的支援功能。

3. 支援的顯示比例

為確保遊戲在不同螢幕大小上都能正確顯示,請先實作各種顯示比例的支援功能。建議調整攝影機或畫布的顯示比例,以配合不同螢幕。

  1. 確認應用程式使用可調整大小的全螢幕設定。
  2. 在AndroidManifest.xml (位於 Assets/Plugins/Android/AndroidManifest.xml):
    1. 設定 android:resizeableActivity="true"。
    2. 設定 android:screenOrientation="fullSensor"。

例如:

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player"
    xmlns:tools="http://schemas.android.com/tools">
    <application>
        <activity android:name="com.unity.lostcryptlargescreenexample.LargeScreenPlayableActivity"
                  android:theme="@style/UnityThemeSelector"
                  android:screenOrientation="fullSensor"
                  android:launchMode="singleTask"
                  android:resizeableActivity="true"
                  android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density"
                  android:hardwareAccelerated="false">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>
    </application>
</manifest>
  1. 在 Unity 中檢查 Android 平台的「Build Settings」設定。

注意:支援各種顯示比例是第一步,可確保遊戲在平板電腦和折疊式裝置上呈現最佳效果。

4. 全螢幕使用率

調整為不同顯示比例後,請確保遊戲使用全螢幕,讓玩家更投入遊戲。

如要使用整個螢幕,請按照下列步驟操作:

  1. 在遊戲的 UI 和攝影機設定中使用錨點。這樣一來,UI 元素就能根據螢幕大小自動調整相對位置。
  2. 在範例專案中開啟「Anchoring」場景,瞭解 UI 畫布錨點的設定方式。
  3. 在「Anchoring」場景中,畫布會更新為可感知安全框,且移動控制項會錨定至畫面角落。

如要維持主相機的顯示比例,請動態調整相機的 pixelRect。CameraAspectLock.cs 指令碼示範如何回應方向變更,以及在攝影機檢視畫面中顯示上下黑邊:

[SerializeField]
private float minAspectRatio = 4f / 3f;

[SerializeField]
private float maxAspectRatio = 21f / 9f;

public void MaintainAspectRatio() {
    int viewWidth = Display.main.systemWidth;
    int viewHeight = Display.main.systemHeight;

    // 1. Calculate screen aspect ratio
    float scaleScreen = viewWidth / (float)viewHeight;
    Rect rect = _camera.pixelRect;

    // 2. Scale to the fullest of the lower between width or height
    if (scaleScreen > maxAspectRatio) {
        // use height, lock width to max at aspect scale
        rect.width = viewHeight * maxAspectRatio;
        rect.height = viewHeight;
    } else if (scaleScreen < minAspectRatio) {
        // use width, lock height to min at aspect scale
        rect.width = viewWidth;
        rect.height = viewWidth / minAspectRatio;
    } else {
        // within allowed aspect ratio range, use full screen
        rect.width = viewWidth;
        rect.height = viewHeight;
    }

    // make sure to center the rect within the window
    rect.x = Mathf.Floor((viewWidth - rect.width) * 0.5f);
    rect.y = Mathf.Floor((viewHeight - rect.height) * 0.5f);

    Debug.Log("camera view width = " + rect.width +
        " height = " + rect.height +
        " x = " + rect.x +
        " y = " + rect.y);

    // 3. Commit the new size to the camera so that it takes effect
    _camera.pixelRect = rect;
}

5. 支援摺疊式裝置

使用摺疊式裝置時,您應根據裝置的摺疊姿勢 (例如 HALF_OPENED、FLAT) 和螢幕大小,即時調整遊戲的版面配置。

  1. 使用 Android 的 Jetpack Window Manager 偵測裝置狀態。
  2. 在範例專案中,開啟 HingeAware 場景。
  3. 這個場景包含 ConfigurationManager MonoBehaviour,可將 Android 的 Jetpack WindowManager 事件橋接至 Unity,並透過 UnityEvent 回呼回應摺疊狀態。
  4. HingeSensor.cs 會使用 com.unity.lostcryptlargescreenexample.HingeAngleSensor Java 外掛程式讀取螢幕轉軸角度。

使用 ConfigurationManager

ConfigurationManager.cs 會與自訂 Android 活動通訊,並剖析代表狀態的 JSON 字串。並監聽 Android Activity 的 onConfigurationChanged 和 onFoldChanged 回呼。

[System.Serializable]
public class FoldInfo {
	public string orientation;
	public string state;
	public int isSeparating;
	public int boundsLeft;
	public int boundsTop;
	public int boundsRight;
	public int boundsBottom;
}

public void onFoldChanged(string strFoldInfo) {
	FoldInfo info = JsonUtility.FromJson<FoldInfo>(strFoldInfo);

	// Always call the refresh from the main Unity thread
	StartCoroutine(ExecuteOnMainUnityThread(ActionOnFoldChange, info));
}

您也可以使用 getFoldableState 屬性,同步查詢狀態:

public static string getFoldableState {
	get {
		if (Application.platform == RuntimePlatform.Android) {
			var foldingFeatureObject = foldablePlayerActivity.Call<AndroidJavaObject>("getFoldingFeature");
			if (foldingFeatureObject != null) {
				var state = foldingFeatureObject.Call<AndroidJavaObject>("getState");
				return state.Call<string>("toString");
			}
		}
		return "NONE";
	}
}

6. 使用 HingeSensor

部分摺疊式裝置配備實體轉軸感應器,可提供摺疊角度 (0 到 360 度)。您可以使用這項功能來驅動遊戲機制或調整攝影機。

在 HingeSensor.cs 中,系統會初始化 Android 外掛程式,以便讀取硬體感應器。你也可以檢查是否已啟用鉸鏈:

public class HingeSensor : IDisposable {
	AndroidJavaObject plugin;

	public static HingeSensor Start() {
		if (Application.platform == RuntimePlatform.Android) {
			return OnPlayer.Run(p => {
				var context = p.GetStatic<AndroidJavaObject>("currentActivity");
				var plugin = new AndroidJavaClass("com.unity.lostcryptlargescreenexample.HingeAngleSensor")
						.CallStatic<AndroidJavaObject>("getInstance", context);

				if (plugin != null) {
					plugin.Call("setupSensor");
					return new HingeSensor(plugin);
				}
				return null;
			});
		}
		return null;
	}

	public float GetHingeAngle() {
		return (Application.platform == RuntimePlatform.Android && plugin != null) ? plugin.Call<float>("getHingeAngle") : -1.0f;
	}

	public bool IsHingeEnabled() {
		return Application.platform == RuntimePlatform.Android && plugin != null && plugin.Call<int>("isHingeEnabled") > 0;
	}
}

注意:應用程式暫停或毀損時,請務必在 HingeSensor 執行個體上呼叫 Dispose() 或 StopSensing(),以免耗盡電池電量。

7. 建立 AAB 檔案

如要在 Unity 編輯器中建立 AAB 檔案,請按照下列步驟操作:

  1. 在 Unity 編輯器中,依序點選「File」>「Build settings」。
  2. 選取「Build App Bundle ( Google Play )」。詳情請參閱「Android Build Settings reference」。
  3. 點選「Build」。
  4. 從 Unity 編輯器下載 AAB 檔案。

建立內部測試版本

如要在 Play 管理中心建立內部測試版本並新增測試人員,請按照下列步驟操作:

  1. 在 Google Play 管理中心選取遊戲。
  2. 前往「測試及發布」頁面 (依序點選「測試」>「內部測試」)。
  3. 按一下「上傳」,然後選取 AAB 檔案。
  4. 在「Release details」(發布詳細資料) 欄位中輸入名稱。
  5. 點選「下一步」並查看發布詳細資料。
  6. 點選「儲存並發布」。

8. 建構並執行專案

現在可以建構專案,並在裝置上測試。

  1. 確認遊戲已開啟。
  2. 在 Play 管理中心中,依序前往「File」>「Build Profile」(或「Build Settings」)。
  3. 如要上傳至 Play 管理中心,請務必勾選「Build App Bundle (Google Play)」,或按一下「Build and Run」,直接部署至已連線的裝置。
  4. 請確認可摺疊裝置,並根據裝置的摺疊姿勢 (例如 HALF_OPENED、FLAT) 和螢幕大小,即時調整遊戲版面配置。

9. 恭喜

您已成功瞭解如何調整 Unity Android 遊戲,使其適用於大螢幕和摺疊式裝置!

問卷調查

我們非常重視您對本程式碼研究室的意見。請花幾分鐘時間填寫問卷調查。