4

示例:如果我在脚本文件中编写以下代码。

#if UNITY_EDITOR
  Debug.Log( "I'll print in Editor only.." );
#endif

我的问题是,在创建 apk 构建时,这部分代码是否会被添加到 apk 构建中,尽管它在 Android 上安装后不会运行,或者统一不会在 apk 构建中包含此代码。

我期待以下答案之一。

  1. 不,unity 不会在 APK 构建中包含此代码。
  2. 是的,unity 会将它包含在 apk 中,但它永远不会在那里运行,只会永远无用地坐在 apk 的某个地方。

附言

问题是关于包括不编译。我无法在其他地方得到明确的答案。

4

3 回答 3

2

-statement 中的代码#if只会在指定的平台上编译。

Unity 包含一个称为平台相关编译的功能。这由一些预处理器指令组成,允许您对脚本进行分区,以专门为一个受支持的平台编译和执行一段代码。

https://docs.unity3d.com/Manual/PlatformDependentCompilation.html

于 2018-06-25T12:50:49.400 回答
2

不,Unity 不会#if UNITY_EDITOR在构建中包含代码。

您可以使用以下示例对此进行测试:

void Start ()
{
    #if UNITY_EDITOR
    Debug.Log("Unity Editor");
    #else
    // note that this block of code is not included while working in the Editor,
    // but it will be included when building to Android
    // (or any other build target outside the editor)
    Debug.Log("Not Unity Editor");
    #endif

    #if UNITY_ANDROID
    Debug.Log("Android");
    #endif

    #if UNITY_STANDALONE_WIN
    Debug.Log("Stand Alone Windows");
    // Including a garbage line of code below to show
    // that code really isn't included with the build
    // when the build target doesn't match, e.g. set to Android
    fkldjsalfjdasfkldjsafsdk;
    #endif
}

如果您的构建目标设置为 Android,尽管编译错误,您的应用程序仍应构建,因为UNITY_STANDALONE_WIN代码已完全删除(并且您的 IDE 可能会使代码块变灰)。将构建目标更改为 Windows 后,代码将无法编译。


(就个人而言,我更喜欢尽可能地使用Application.isEditorover #if UNITY_EDITORmacro 作为一种习惯,因为使用#if UNITY_EDITORwith#else可能会导致您中断构建,直到稍后才意识到任何无法在 #else 块中编译的代码。我通常更担心关于这一点,而不是在我的构建中包含额外的无用代码。当然,在使用UnityEditor类时,使用#if UNITY_EDITOR是不可避免的。)

于 2018-06-25T13:34:44.863 回答
1

不,unity 不会在 APK 构建中包含此代码。

于 2018-06-25T12:50:07.353 回答