主題

[Unity] 讀取 Argument

[桐生會]永和豆漿 | 2021-06-19 21:04:47 | 巴幣 0 | 人氣 150

目標:
透過讀取Argument的方式,決定是否啟用VR模式
程式碼:
使用:
System.Environment.GetCommandLineArgs();
文檔連結
測試:
using UnityEngine;

public class arg_test : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log(GetArg("-test"));
    }

    private string GetArg(string name)
    {
        var args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == name && args.Length > i + 1)
            {
                return args[i + 1];
            }
        }
        return "null";
    }
}
實作:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Management;

public class VR_ModeDetect : MonoBehaviour
{
    public static MainControl instace = null;
    public bool UsingVR = false;
    
    public Canvas MainScreen;
    public Camera VRCamera;
    public Camera FlatCamera;
    public GameObject Player_Component;

    private void Awake()
    {
        //XRSettings.enabled = UsingVR;
        Debug.Log($"VR Mode is {UsingVR}");
        Debug.LogWarning($"The cmd line is :{GetArg("-Test")}");
        if (UsingVR == true || GetArg("-VR").ToLower() == "true")
        {
            XRGeneralSettings.Instance.Manager.InitializeLoaderSync();
            XRGeneralSettings.Instance.Manager.StartSubsystems();
            MainScreen.renderMode = RenderMode.WorldSpace;
            MainScreen.worldCamera = VRCamera;
            Player_Component.transform.SetParent(VRCamera.transform);
        }
        else
        {
            MainScreen.renderMode = RenderMode.ScreenSpaceOverlay;
            MainScreen.worldCamera = FlatCamera;
            Player_Component.transform.SetParent(FlatCamera.transform);
        }
    }

    private string GetArg(string name)
    {
        var args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == name && args.Length > i + 1)
            {
                return args[i + 1];
            }
        }
        return "null";
    }
}
將程式碼執行順序調到最前面

結果:

創作回應

更多創作