In-depth understanding of Unity's Application class: a detailed technical guide (2)

During the development of Unity, sometimes we need to obtain or manipulate the information of the current application, such as the application version, operating environment, whether it is running in the foreground, etc. Unity provides a very powerful class called Application, which can help us easily obtain this information.

Application overview

Unity's Application class provides a way to get and manipulate information about the current application. This includes the application's identifier, version, operating platform, data path, etc., and also provides methods such as exiting the application. All its properties and methods are static, so you don't need to create an Application object.

Let's take a look at the important properties and methods of the Application class:

  1. Application information:
    identifier: Returns the package name or bundle of the application identifier
    version: Returns the version number of the application
    unityVersion: Returns the version number of Unity currently running
    productName: Returns the product name of the application
    companyName: Returns the company name of the application

identifier:

This property returns the application's identifier, which is the PackageName package name. It may return a string like "com.company.game", for iOS and Android, this is a unique string used to identify the installation package of the application on the device.

string appId = Application.identifier;
Debug.Log(appId);  // 输出:com.company.game

version:

This property returns the version number of the application, which is the version number you set when publishing the application.

string appVersion = Application.version;
Debug.Log(appVersion);  // 输出:1.0.0

unityVersion:

This read-only property returns the version number of the currently running Unity. This property is often used to detect the Unity version to determine whether certain version-specific functions can be used

string unityVersion = Application.unityVersion;
Debug.Log(unityVersion);  // 输出示例:2023.1.0f1

productName:

This property returns the application's product name

string productName = Application.productName;
Debug.Log(productName);  // 输出:My Game

companyName:

This property returns the application's company name

string companyName = Application.companyName;
Debug.Log(companyName);  // 输出:My Company

  1. Related to the running environment:
    isEditor: if the current application is running in the Unity editor, the value is true
    isFocused: if the current application has the focus, the value is true
    isPlaying: if the current application is running (not suspended or exited), the value is The value is true
    isMobilePlatform: If the current application is running on a mobile device, the value is true
    platform: Returns the platform on which the application is running

isEditor:

This property tells you whether the application is running in the Unity editor, which is useful for different behaviors in the editor and on actual devices.

if (Application.isEditor) {
    
    
    Debug.Log("在编辑器中运行");
} else {
    
    
    Debug.Log("在实际设备上运行");
}

isFocused:

This property tells you whether the application window has the input focus. If the user is interacting with your application, it has focus; if the user switches to another application, then your application loses focus.

if (Application.isFocused) {
    
    
    Debug.Log("应用程序拥有焦点");
} else {
    
    
    Debug.Log("应用程序失去了焦点");
}

isPlaying:

This property tells you whether the application is running. If the application is running, this value is true; if the application is suspended or has exited, then this value is false.

if (Application.isPlaying) {
    
    
    Debug.Log("应用程序正在运行");
} else {
    
    
    Debug.Log("应用程序已暂停或退出");
}

isMobilePlatform:

This attribute can tell you whether the application is running on a mobile device, such as an Android or iOS device.

if (Application.isMobilePlatform) {
    
    
    Debug.Log("在移动设备上运行");
} else {
    
    
    Debug.Log("不在移动设备上运行");
}

platform:

This property returns the platform the application is running on. This value is an enumeration, and the values ​​include: WindowsPlayer, Android, IPhonePlayer, etc.

RuntimePlatform platform = Application.platform;
Debug.Log(platform);  // 输出:WindowsPlayer

  1. Data path related:
    dataPath: Returns the data path of the application, which is used to store the data of the application.
    persistentDataPath: Returns a persistent data path, where the application can safely write files.
    streamingAssetsPath: Returns a path to the StreamingAssets folder. This folder is used to store resources that need to be distributed with the application.
    temporaryCachePath: Returns a temporary cache path, which is used to store temporary files that can be deleted at any time.

dataPath:

This property returns the application's data path, which is used to store the application's data. For example, it can be used to find your application's resource files

string dataPath = Application.dataPath;
Debug.Log(dataPath);  // 输出:C:\Users\user\Documents\myGame\Assets

persistentDataPath:

This property returns a path to persistent data, where the application can safely write files, and these files still exist after the application is updated or uninstalled

string persistentDataPath = Application.persistentDataPath;
Debug.Log(persistentDataPath);  // 输出:C:\Users\user\AppData\LocalLow\company\game

streamingAssetsPath:

This property returns a path to the StreamingAssets folder. This folder is used to store resources that need to be distributed with the application, such as audio, video or text files

string streamingAssetsPath = Application.streamingAssetsPath;
Debug.Log(streamingAssetsPath);  // 输出:C:\Users\user\Documents\myGame\Assets\StreamingAssets

temporaryCachePath:

This property returns the path of a temporary cache, which is used to store temporary files that can be deleted at any time.

string temporaryCachePath = Application.temporaryCachePath;
Debug.Log(temporaryCachePath);  // 输出:C:\Users\user\AppData\Local\Temp\company\game

  1. App action related:
    runInBackground: If set to true, the app will keep running when it loses focus; otherwise, it will pause.
    Quit(): It is used to exit the application.
    LoadLevel(): It is used for loading different scenarios of the application. 目前已弃用该API
    targetFrameRate: This property can set or get the target frame rate of the application

runInBackground:

This property can set whether the application continues to run when it loses focus (whether it can run in the background). If set to true, the application will continue running when it loses focus; otherwise, it will pause.

Application.runInBackground = true;  // 应用程序在后台运行

Quit():

This method is used to exit the application. Note that in the Unity editor, this method does not close the editor.

Application.Quit();  // 退出应用程序

LoadLevel():

This method is used to load different scenarios of the application. 目前已弃用该API, use insteadSceneManager.LoadScene()

targetFrameRate:

This property can set or get the target frame rate of the application. When this value is -1, Unity will refresh the frame as fast as possible

Application.targetFrameRate = 60; // 将目标帧率设置为60

  1. Other related:
    systemLanguage: This attribute returns the language of the user's operating system
    internetReachability: This attribute returns the Internet reachability status of the device
    InstallMode: This attribute returns how the application was installed on the user's device
    installerName: Returns the program used to install the application Name
    OpenURL(string url): This method will try to open the specified url with the system default browser
    RequestAdvertisingIdentifierAsync(): This method requests the advertising identifier asynchronously

systemLanguage:

This property returns the language of the user's operating system. This can be used to automatically set the game's language

SystemLanguage language = Application.systemLanguage;
Debug.Log(language);  // 输出:English

internetReachability:

This property returns the Internet status of the device. It can tell you if the device is connected to the internet and if the device is connected via WIFI or mobile data

NetworkReachability reachability = Application.internetReachability;
Debug.Log(reachability);  // 输出:ReachableViaWiFi

InstallMode:

This property returns how the application was installed on the user's device. It returns an enumeration value, this value may be Unknown, Store or DeveloperBuild

ApplicationInstallMode installMode = Application.installMode;
Debug.Log(installMode);  // 输出:Store

installerName:

This read-only property returns the name of the program used to install the application, which is mainly used for specific distribution channels

string installerName = Application.installerName;
Debug.Log(installerName);  // 输出示例:Google Play

OpenURL(string url):

This method will try to open the specified url with the system default browser

Application.OpenURL("https://www.XXX.com");

RequestAdvertisingIdentifierAsync():

This method requests the advertising identifier asynchronously. The advertising identifier is a string that can be used to display targeted advertising for the device

StartCoroutine(GetAdId());

IEnumerator GetAdId()
{
    
    
    yield return Application.RequestAdvertisingIdentifierAsync(
        (string advertisingId, bool trackingEnabled, string error) =>
        {
    
    
            Debug.Log("advertisingId:" + advertisingId + " " + "trackingEnabled:" + trackingEnabled + " " + error);
        }
    );
}

  1. Rarely used:
    absoluteURL: Returns the absolute URL of the application
    SetBuildTags(string[] buildTags): This static method can set the built tags
    GetBuildTags(): This static method returns a string array containing the built tags
    GetStackTraceLogType(LogType logType) : Get the stack trace recording method of the specified type of log.
    SetStackTraceLogType(LogType logType, StackTraceLogType stackTraceType): Set the stack trace recording method of the specified type of log.

absoluteURL:

This is a read-only property that returns the absolute URL of the application, for web players. forGames built with WebGL, this attribute can help you get the current URL address of the game.

string absoluteURL = Application.absoluteURL;
Debug.Log(absoluteURL);  // 输出示例:http://www.XXX.com/mygame

SetBuildTags(string[] buildTags):

This static method can set the build's tags. Build labels are labels set for the application during the build process and can be used to identify or filter builds. For example, you might use build tags to differentiate development from production, or to differentiate regions or different versions of content.

string[] buildTags = new string[] {
    
    "tag1", "tag2", "tag3"};
Application.SetBuildTags(buildTags);

Note that the SetBuildTags method is typically used in editor scripts, not in game runtime code, as changing build tags at runtime may have no real effect.
 

GetBuildTags():

This static method returns a string array containing the built labels. Build labels are labels set for the application during the build process and can be used to identify or filter builds. For example, you might use build tags to differentiate development from production, or to differentiate regions or different versions of content.

string[] buildTags = Application.GetBuildTags();
foreach (string tag in buildTags)
{
    
    
    Debug.Log(tag);
}

This code will print out all build tags for the app in the Unity console
 

GetStackTraceLogType(LogType logType)和 SetStackTraceLogType(LogType logType, StackTraceLogType stackTraceType):

These two methods get and set how stack traces are recorded for logs of the specified type.

// 获取当前LogType.Error的堆栈跟踪记录方式
StackTraceLogType currentStackTraceLogType = Application.GetStackTraceLogType(LogType.Error);
Debug.Log(currentStackTraceLogType);  // 输出示例:ScriptOnly

// 设置LogType.Error的堆栈跟踪记录方式为全堆栈跟踪
Application.SetStackTraceLogType(LogType.Error, StackTraceLogType.Full);

The above are the properties and methods of Unity's Application class. Some properties or methods have been deprecated, so I won't explain them one by one here. This class can help you better understand and control your application during development. Hope this in-depth analysis and usage analysis can help you.

Guess you like

Origin blog.csdn.net/qq_33795300/article/details/131364030