Version: 2019.1
Understanding Automatic Memory Management
Специальные папки и порядок компиляции скриптов

Platform dependent compilation

Unity includes a feature called Platform Dependent Compilation. This consists of some preprocessor directives that let you partition your scripts to compile and execute a section of code exclusively for one of the supported platforms.

Кроме того, вы можете запустить этот код в редакторе, таким образом, вы можете скомпилировать код специально для вашего мобильного/консоли и проверить его в редакторе!

Platform #define directives

Определения платформ для ваших скриптов, которые Unity поддерживает:

Property: Function:
UNITY_EDITOR Определение для вызова скриптов редактора Unity из вашего игрового кода.
UNITY_EDITOR_WIN Определение платформы для редактора кода на Windows.
UNITY_EDITOR_OSX #define directive for Editor code on Mac OS X.
UNITY_STANDALONE_OSX #define directive for compiling/executing code specifically for Mac OS X (including Universal, PPC and Intel architectures).
UNITY_STANDALONE_WIN Используйте, когда вы хотите скомпилировать/выполнить код для приложения на Windows.
UNITY_STANDALONE_LINUX Используйте, когда вы хотите скомпилировать/выполнить код для приложения на Linux.
UNITY_STANDALONE #define directive for compiling/executing code for any standalone platform (Mac OS X, Windows or Linux).
UNITY_WII Определение платформы для компиляции/выполнения кода для консоли Wii.
UNITY_IOS Определение платформы для компиляции/выполнения кода для iPhone.
UNITY_IPHONE Deprecated. Use UNITY_IOS instead.
UNITY_ANDROID Определение платформы для Android.
UNITY_PS4 Определение платформы для запуска кода на PlayStation 3.
UNITY_XBOXONE Определение платформы для выполнения кода на Xbox One.
UNITY_TIZEN Определение платформы для Tizen.
UNITY_TVOS Определение платформы для Apple TV.
UNITY_WSA #define directive for Universal Windows Platform. Additionally, NETFX_CORE is defined when compiling C# files against .NET Core and using .NET scripting backend.
UNITY_WSA_10_0 #define directive for Universal Windows Platform. Additionally WINDOWS_UWP is defined when compiling C# files against .NET Core.
UNITY_WINRT Same as UNITY_WSA.
UNITY_WINRT_10_0 Equivalent to UNITY_WSA_10_0
UNITY_WEBGL Определение платформы для Windows Phone 8.
UNITY_FACEBOOK #define directive for the Facebook platform (WebGL or Windows standalone).
UNITY_ADS Определение для вызова скриптов редактора Unity из вашего игрового кода.
UNITY_ANALYTICS Определение для вызова скриптов редактора Unity из вашего игрового кода.
UNITY_ASSERTIONS #define directive for assertions control process.

From Unity 2.6.0 onwards, you can compile code selectively. The options available depend on the version of the Editor that you are working on. Given a version number X.Y.Z (for example, 2.6.0), Unity exposes three global #define directives in the following formats: UNITY_X, UNITY_X_Y and UNITY_X_Y_Z.

Here is an example of #define directives exposed in Unity 5.0.1:

UNITY_5 Определение платформы для мажор-версии Unity 2.6.
UNITY_5_0 Определение платформы для мажор-версии Unity 3.0.
UNITY_5_0_1 Определение платформы для мажор-версии Unity 3.0.

Starting from Unity 5.3.4, you can compile code selectively based on the earliest version of Unity required to compile or execute a given portion of code. Given the same version format as above (X.Y.Z), Unity exposes one global #define in the format UNITY_X_Y_OR_NEWER, that can be used for this purpose.

The supported #define directives are:

CSHARP_7_3_OR_NEWER Defined when building scripts with support for C# 7.3 or newer.
ENABLE_MONO Scripting backend #define for Mono.
ENABLE_IL2CPP Scripting backend #define for IL2CPP.
NET_2_0 Defined when building scripts against .NET 2.0 API compatibility level on Mono and IL2CPP.
NET_2_0_SUBSET Defined when building scripts against .NET 2.0 Subset API compatibility level on Mono and IL2CPP.
NET_LEGACY Defined when building scripts against .NET 2.0 or .NET 2.0 Subset API compatibility level on Mono and IL2CPP.
NET_4_6 Defined when building scripts against .NET 4.x API compatibility level on Mono and IL2CPP.
NET_STANDARD_2_0 Defined when building scripts against .NET Standard 2.0 API compatibility level on Mono and IL2CPP.
ENABLE_WINMD_SUPPORT Defined when Windows Runtime support is enabled on IL2CPP. See Windows Runtime Support for more details.

You use the DEVELOPMENT_BUILD #define to identify whether your script is running in a player which was built with the “Development Build” option enabled.

You can also compile code selectively depending on the scripting back-end.

Тестирование прекомпилированного кода.

Мы собираемся показать небольшой пример, как использовать прекомпилированный код. В данном примере просто выводится сообщение в зависимости от платформы, которую вы выбрали в качестве целевой для сборки.

First of all, select the platform you want to test your code against by going to File > Build Settings. This displays the Build Settings window; select your target platform from here.

Build Settings window with PC, Mac & Linux selected as the target platforms
Build Settings window with PC, Mac & Linux selected as the target platforms

Выберите платформу, для который вы хотите проверить ваш прекомпилированный код, и нажмите кнопку Switch Editor, тем самым указывая Unity целевую платформу.

Создайте скрипт и скопируйте этот код:-

// C#
using UnityEngine;
using System.Collections;

public class PlatformDefines : MonoBehaviour {
  void Start () {

    #if UNITY_EDITOR
      Debug.Log("Unity Editor");
    #endif
    
    #if UNITY_IOS
      Debug.Log("Iphone");
    #endif

    #if UNITY_STANDALONE_OSX
    Debug.Log("Stand Alone OSX");
    #endif

    #if UNITY_STANDALONE_WIN
      Debug.Log("Stand Alone Windows");
    #endif

  }          
}

To test the code, click Play Mode. Confirm that the code works by checking for the relevant message in the Unity console, depending on which platform you selected - for example, if you choose iOS, the message “Iphone” is set to appear in the console.

In C# you can use a CONDITIONAL attribute which is a more clean, less error-prone way of stripping out functions. See ConditionalAttribute Class for more information. Note that common Unity callbacks (ex. Start(), Update(), LateUpdate(), FixedUpdate(), Awake()) are not affected by this attribute because they are called directly from the engine and, for performance reasons, it does not take them into account.

In addition to the basic #if compiler directive, you can also use a multiway test in C#:


#if UNITY_EDITOR
    Debug.Log("Unity Editor");

#elif UNITY_IOS
    Debug.Log("Unity iPhone");

#else
    Debug.Log("Any other platform");

#endif


Platform custom #defines

It is also possible to add to the built-in selection of #define directives by supplying your own. Open the Other Settings panel of the Player settings and navigate to the Scripting Define Symbols text box.

Здесь вы можете указать имена обозначений, которые хотите определить для конкретной платформы, через точку с запятой. Эти обозначения можно затем использовать в качестве условий для директив #if также как встроенные.

Global custom #defines

Вы можете определить свои собственные директивы препроцессора, чтобы контролировать, какой код попадет в результат при компиляции. Для этого необходимо добавить текстовый файл с дополнительными директивами в папку “Assets/”. Имя файла зависит от языка, который вы используете, а расширение rsp.:

C# (player and editor scripts) <Project Path>/Assets/mcs.rsp

As an example, if you include the single line -define:UNITY_DEBUG in your mcs.rsp file, the #define directive UNITY_DEBUG exists as a global #define for C# scripts, except for Editor scripts.

Every time you make changes to .rsp files, you need to recompile in order for them to be effective. You can do this by updating or reimporting a single script (.js or .cs) file.

NOTE

If you want to modify only global #define directives, use Scripting Define Symbols in Player settings, because this covers all the compilers. If you choose the .rsp files instead, you need to provide one file for every compiler Unity uses.

The use of .rsp files is described in the ‘Help’ section of the mcs application, which is included in the Editor installation folder. You can get more information by running mcs -help.

Note that the .rsp file needs to match the compiler being invoked. For example:

  • when targeting the .NET 3.5 Equivalent (deprecated) scripting runtime version, mcs is used with mcs.rsp, and
  • when targeting the .NET 4.x Eqivalent scripting runtime version compiler, csc is used with csc.rsp.

  • 2018–03–16 Page amended with no editorial review

  • Removed Samsung TV support.

Understanding Automatic Memory Management
Специальные папки и порядок компиляции скриптов
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961