【2023/05版】UnityでAndroidビルド失敗．原因はTarget API Levelだった!?

Unityでプロジェクト完成後，apk出力しようと思ったら，エラー発生．
ネット上の解決法を全部試したけど，エラー＆エラー＆エラー．
諦めようとした時，あることを知ってやっとapkビルドできるようになったので，まとめます．

:::note
実は，Windows版のUnityでビルドすれば，（なぜか）何もせずにapkに出力できます．
しかし，MacBook <=> Windowsの往復は面倒くさい．そのため，Macbookで完結させようとした次第です．
:::

# 開発環境
* MacBook Pro 16inch (Ventura 13.3.1)
* Unity 2019.4.40f1

# 現在の状況
* Androidビルドするにあたり，`Android Build Support`を[UnityHub](https://unity.com/ja/download)から導入してある．
* これに含まれている`OpenJDK`と`Android SDK & NDK tools`もインストールしてある．

<img width=600px src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/1120abcc-77a4-eb01-9ae3-a1b00e09d661.png">


::: note
<INS>一致している必要はありません</INS>が，私の場合は，
`Settings > External Tools`のAndroidのところはデフォルトのままです．**GradleやSDK等のアップデート等は何も行っていません．**
<img width=1000px src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/a96345f5-dd5f-7296-aa28-9f553fbcc7ba.png">
:::

# エラー
まだエラーが発生するとも知らないので，とりあえずビルド．
<img width=200px src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/8e394816-0894-31b4-677c-b772d44a1db6.png">

はい，皆さんご存じ，エラーです．
（エラーの意味はご自身で翻訳してください．そこまで大切な内容ではないです）

```text:上記ポップアップ内容
More than one file was found with OS independent path 'META-INF/com.android.tools/proguard/coroutines.pro' See the Console for details.
```

::: note warn
`META-INF/com.android.tools/proguard/coroutines.pro`の部分は**人それぞれ**だと思います．あくまで**一例**と考えてください．
:::

コンソールを見てみると，５つのエラーが発生しています．
<img width=900px src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/51b91864-d94a-dd12-eb7c-d178b782ec6f.png">

:::note
上記エラーの全文です．見たければどうぞ．

<details>
<summary>エラー１（クリックで展開）</summary>

```text
> Task :unityLibrary:FirebaseApp.androidlib:preBuild UP-TO-DATE
> Task :unityLibrary:preBuild UP-TO-DATE
> Task :launcher:preBuild UP-TO-DATE
> Task :unityLibrary:FirebaseApp.androidlib:preReleaseBuild UP-TO-DATE
> Task :unityLibrary:preReleaseBuild UP-TO-DATE
> Task :launcher:prepareLintJar
> Task :unityLibrary:checkReleaseManifest
> Task :unityLibrary:FirebaseApp.androidlib:checkReleaseManifest
> Task :unityLibrary:FirebaseApp.androidlib:processReleaseManifest
> Task :unityLibrary:processReleaseManifest
> Task :unityLibrary:packageReleaseRenderscript NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseAidl NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:packageReleaseRenderscript NO-SOURCE
> Task :unityLibrary:generateReleaseBuildConfig
> Task :unityLibrary:compileReleaseAidl NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseRenderscript NO-SOURCE
> Task :unityLibrary:compileReleaseRenderscript NO-SOURCE
> Task :unityLibrary:generateReleaseResValues
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseResValues
> Task :unityLibrary:generateReleaseResources
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseResources
> Task :unityLibrary:FirebaseApp.androidlib:packageReleaseResources
> Task :unityLibrary:packageReleaseResources
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseRFile
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseBuildConfig
> Task :unityLibrary:FirebaseApp.androidlib:prepareLintJar
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseSources
> Task :unityLibrary:FirebaseApp.androidlib:javaPreCompileRelease
> Task :launcher:preReleaseBuild
> Task :launcher:compileReleaseAidl NO-SOURCE
> Task :launcher:compileReleaseRenderscript NO-SOURCE
> Task :launcher:checkReleaseManifest
> Task :launcher:generateReleaseBuildConfig
> Task :launcher:generateReleaseSources
> Task :launcher:mainApkListPersistenceRelease
> Task :launcher:generateReleaseResValues
> Task :launcher:generateReleaseResources
> Task :unityLibrary:generateReleaseRFile
> Task :unityLibrary:prepareLintJar
> Task :unityLibrary:generateReleaseSources
> Task :unityLibrary:prepareLintJarForPublish
> Task :unityLibrary:mergeReleaseShaders
> Task :unityLibrary:compileReleaseShaders
> Task :unityLibrary:generateReleaseAssets
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseJavaWithJavac
> Task :unityLibrary:FirebaseApp.androidlib:bundleLibCompileRelease
> Task :unityLibrary:FirebaseApp.androidlib:prepareLintJarForPublish
> Task :unityLibrary:FirebaseApp.androidlib:mergeReleaseShaders
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseShaders
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseAssets
> Task :unityLibrary:FirebaseApp.androidlib:packageReleaseAssets
> Task :unityLibrary:FirebaseApp.androidlib:bundleLibRuntimeRelease
> Task :unityLibrary:FirebaseApp.androidlib:processReleaseJavaRes NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:bundleLibResRelease
> Task :unityLibrary:FirebaseApp.androidlib:mergeReleaseJniLibFolders
> Task :unityLibrary:FirebaseApp.androidlib:transformNativeLibsWithMergeJniLibsForRelease
> Task :unityLibrary:FirebaseApp.androidlib:transformNativeLibsWithIntermediateJniLibsForRelease
> Task :unityLibrary:packageReleaseAssets
> Task :unityLibrary:javaPreCompileRelease
> Task :launcher:mergeReleaseResources
> Task :launcher:createReleaseCompatibleScreenManifests
> Task :launcher:processReleaseManifest

> Task :unityLibrary:compileReleaseJavaWithJavac

> Task :unityLibrary:bundleLibCompileRelease
> Task :unityLibrary:bundleLibRuntimeRelease
> Task :unityLibrary:processReleaseJavaRes NO-SOURCE
> Task :unityLibrary:bundleLibResRelease
> Task :launcher:processReleaseResources
> Task :launcher:javaPreCompileRelease
> Task :unityLibrary:mergeReleaseJniLibFolders
> Task :unityLibrary:transformNativeLibsWithMergeJniLibsForRelease
> Task :launcher:compileReleaseJavaWithJavac
> Task :launcher:compileReleaseSources
> Task :unityLibrary:transformNativeLibsWithIntermediateJniLibsForRelease
> Task :launcher:lintVitalRelease
> Task :launcher:mergeReleaseShaders
> Task :launcher:compileReleaseShaders
> Task :launcher:generateReleaseAssets
> Task :launcher:mergeReleaseAssets
> Task :launcher:validateSigningRelease
> Task :launcher:signingConfigWriterRelease
> Task :launcher:checkReleaseDuplicateClasses
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/org.jetbrains.kotlinx.kotlinx-coroutines-core-jvm-1.6.1.jar: D8: Type `sun.misc.Signal` was not found, it is required for default or static interface methods desugaring of `void kotlinx.coroutines.debug.AgentPremain.installSignalHandler()`
D8: synthesized for lambda desugaring: Interface `sun.misc.SignalHandler` not found. It's needed to make sure desugaring of `kotlinx.coroutines.debug.-$$Lambda$AgentPremain$6vy0kBIPkuO0a1izx5ONKfM-3Ss` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Type `com.google.android.play.core.assetpacks.AssetPackManagerFactory` was not found, it is required for default or static interface methods desugaring of `void com.unity3d.player.a.<init>(android.content.Context)`
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.tasks.OnCompleteListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$d` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/org.jetbrains.kotlinx.kotlinx-coroutines-core-jvm-1.6.1.jar: D8: Interface `java.lang.instrument.ClassFileTransformer` not found. It's needed to make sure desugaring of `kotlinx.coroutines.debug.AgentPremain$DebugProbesTransformer` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.tasks.OnCompleteListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$e` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.tasks.OnSuccessListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$c` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.assetpacks.AssetPackStateUpdateListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$b` is correct. Desugaring will assume that this interface has no default method.
> Task :launcher:transformClassesWithDexBuilderForRelease
> Task :launcher:transformDexArchiveWithExternalLibsDexMergerForRelease
> Task :launcher:transformDexArchiveWithDexMergerForRelease
> Task :launcher:mergeReleaseJniLibFolders
> Task :launcher:transformNativeLibsWithMergeJniLibsForRelease
> Task :launcher:processReleaseJavaRes NO-SOURCE
> Task :launcher:transformResourcesWithMergeJavaResForRelease FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.1.1/userguide/command_line_interface.html#sec:command_line_warnings
63 actionable tasks: 63 executed

UnityEngine.GUIUtility:ProcessEvent (int,intptr) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:197)

```
</details>

<details><summary>エラー２（クリックで展開）</summary>

```text
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
注意:/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/src/main/java/com/unity3d/player/UnityPlayerActivity.javaは非推奨のAPIを使用またはオーバーライドしています。
注意:詳細は、-Xlint:deprecationオプションを指定して再コンパイルしてください。

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':launcher:transformResourcesWithMergeJavaResForRelease'.
> More than one file was found with OS independent path 'META-INF/com.android.tools/proguard/coroutines.pro'

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 16s

UnityEngine.GUIUtility:ProcessEvent (int,intptr) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:197)
```

</details>

<details><summary>エラー3（クリックで展開）</summary>

```text
CommandInvokationFailure: Gradle build failed.
/Applications/Unity/Hub/Editor/2019.4.40f1/PlaybackEngines/AndroidPlayer/OpenJDK/bin/java -classpath "/Applications/Unity/Hub/Editor/2019.4.40f1/PlaybackEngines/AndroidPlayer/Tools/gradle/lib/gradle-launcher-5.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

stderr[
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
注意:/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/src/main/java/com/unity3d/player/UnityPlayerActivity.javaは非推奨のAPIを使用またはオーバーライドしています。
注意:詳細は、-Xlint:deprecationオプションを指定して再コンパイルしてください。

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':launcher:transformResourcesWithMergeJavaResForRelease'.
> More than one file was found with OS independent path 'META-INF/com.android.tools/proguard/coroutines.pro'

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 16s
]
stdout[
> Task :unityLibrary:FirebaseApp.androidlib:preBuild UP-TO-DATE
> Task :unityLibrary:preBuild UP-TO-DATE
> Task :launcher:preBuild UP-TO-DATE
> Task :unityLibrary:FirebaseApp.androidlib:preReleaseBuild UP-TO-DATE
> Task :unityLibrary:preReleaseBuild UP-TO-DATE
> Task :launcher:prepareLintJar
> Task :unityLibrary:checkReleaseManifest
> Task :unityLibrary:FirebaseApp.androidlib:checkReleaseManifest
> Task :unityLibrary:FirebaseApp.androidlib:processReleaseManifest
> Task :unityLibrary:processReleaseManifest
> Task :unityLibrary:packageReleaseRenderscript NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseAidl NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:packageReleaseRenderscript NO-SOURCE
> Task :unityLibrary:generateReleaseBuildConfig
> Task :unityLibrary:compileReleaseAidl NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseRenderscript NO-SOURCE
> Task :unityLibrary:compileReleaseRenderscript NO-SOURCE
> Task :unityLibrary:generateReleaseResValues
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseResValues
> Task :unityLibrary:generateReleaseResources
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseResources
> Task :unityLibrary:FirebaseApp.androidlib:packageReleaseResources
> Task :unityLibrary:packageReleaseResources
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseRFile
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseBuildConfig
> Task :unityLibrary:FirebaseApp.androidlib:prepareLintJar
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseSources
> Task :unityLibrary:FirebaseApp.androidlib:javaPreCompileRelease
> Task :launcher:preReleaseBuild
> Task :launcher:compileReleaseAidl NO-SOURCE
> Task :launcher:compileReleaseRenderscript NO-SOURCE
> Task :launcher:checkReleaseManifest
> Task :launcher:generateReleaseBuildConfig
> Task :launcher:generateReleaseSources
> Task :launcher:mainApkListPersistenceRelease
> Task :launcher:generateReleaseResValues
> Task :launcher:generateReleaseResources
> Task :unityLibrary:generateReleaseRFile
> Task :unityLibrary:prepareLintJar
> Task :unityLibrary:generateReleaseSources
> Task :unityLibrary:prepareLintJarForPublish
> Task :unityLibrary:mergeReleaseShaders
> Task :unityLibrary:compileReleaseShaders
> Task :unityLibrary:generateReleaseAssets
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseJavaWithJavac
> Task :unityLibrary:FirebaseApp.androidlib:bundleLibCompileRelease
> Task :unityLibrary:FirebaseApp.androidlib:prepareLintJarForPublish
> Task :unityLibrary:FirebaseApp.androidlib:mergeReleaseShaders
> Task :unityLibrary:FirebaseApp.androidlib:compileReleaseShaders
> Task :unityLibrary:FirebaseApp.androidlib:generateReleaseAssets
> Task :unityLibrary:FirebaseApp.androidlib:packageReleaseAssets
> Task :unityLibrary:FirebaseApp.androidlib:bundleLibRuntimeRelease
> Task :unityLibrary:FirebaseApp.androidlib:processReleaseJavaRes NO-SOURCE
> Task :unityLibrary:FirebaseApp.androidlib:bundleLibResRelease
> Task :unityLibrary:FirebaseApp.androidlib:mergeReleaseJniLibFolders
> Task :unityLibrary:FirebaseApp.androidlib:transformNativeLibsWithMergeJniLibsForRelease
> Task :unityLibrary:FirebaseApp.androidlib:transformNativeLibsWithIntermediateJniLibsForRelease
> Task :unityLibrary:packageReleaseAssets
> Task :unityLibrary:javaPreCompileRelease
> Task :launcher:mergeReleaseResources
> Task :launcher:createReleaseCompatibleScreenManifests
> Task :launcher:processReleaseManifest

> Task :unityLibrary:compileReleaseJavaWithJavac

> Task :unityLibrary:bundleLibCompileRelease
> Task :unityLibrary:bundleLibRuntimeRelease
> Task :unityLibrary:processReleaseJavaRes NO-SOURCE
> Task :unityLibrary:bundleLibResRelease
> Task :launcher:processReleaseResources
> Task :launcher:javaPreCompileRelease
> Task :unityLibrary:mergeReleaseJniLibFolders
> Task :unityLibrary:transformNativeLibsWithMergeJniLibsForRelease
> Task :launcher:compileReleaseJavaWithJavac
> Task :launcher:compileReleaseSources
> Task :unityLibrary:transformNativeLibsWithIntermediateJniLibsForRelease
> Task :launcher:lintVitalRelease
> Task :launcher:mergeReleaseShaders
> Task :launcher:compileReleaseShaders
> Task :launcher:generateReleaseAssets
> Task :launcher:mergeReleaseAssets
> Task :launcher:validateSigningRelease
> Task :launcher:signingConfigWriterRelease
> Task :launcher:checkReleaseDuplicateClasses
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/org.jetbrains.kotlinx.kotlinx-coroutines-core-jvm-1.6.1.jar: D8: Type `sun.misc.Signal` was not found, it is required for default or static interface methods desugaring of `void kotlinx.coroutines.debug.AgentPremain.installSignalHandler()`
D8: synthesized for lambda desugaring: Interface `sun.misc.SignalHandler` not found. It's needed to make sure desugaring of `kotlinx.coroutines.debug.-$$Lambda$AgentPremain$6vy0kBIPkuO0a1izx5ONKfM-3Ss` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Type `com.google.android.play.core.assetpacks.AssetPackManagerFactory` was not found, it is required for default or static interface methods desugaring of `void com.unity3d.player.a.<init>(android.content.Context)`
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.tasks.OnCompleteListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$d` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/org.jetbrains.kotlinx.kotlinx-coroutines-core-jvm-1.6.1.jar: D8: Interface `java.lang.instrument.ClassFileTransformer` not found. It's needed to make sure desugaring of `kotlinx.coroutines.debug.AgentPremain$DebugProbesTransformer` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.tasks.OnCompleteListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$e` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.tasks.OnSuccessListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$c` is correct. Desugaring will assume that this interface has no default method.
/Users/[ユーザ名]/Desktop/UNITY-FOLDER/[プロジェクト名]/Temp/gradleOut/unityLibrary/libs/unity-classes.jar: D8: Interface `com.google.android.play.core.assetpacks.AssetPackStateUpdateListener` not found. It's needed to make sure desugaring of `com.unity3d.player.a$b` is correct. Desugaring will assume that this interface has no default method.
> Task :launcher:transformClassesWithDexBuilderForRelease
> Task :launcher:transformDexArchiveWithExternalLibsDexMergerForRelease
> Task :launcher:transformDexArchiveWithDexMergerForRelease
> Task :launcher:mergeReleaseJniLibFolders
> Task :launcher:transformNativeLibsWithMergeJniLibsForRelease
> Task :launcher:processReleaseJavaRes NO-SOURCE
> Task :launcher:transformResourcesWithMergeJavaResForRelease FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.1.1/userguide/command_line_interface.html#sec:command_line_warnings
63 actionable tasks: 63 executed
]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.AndroidJavaTools.RunJava (System.String args, System.String workingdir, System.Action`1[T] progress, System.String error) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
Rethrow as GradleInvokationException: Gradle build failed
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
Rethrow as BuildFailedException: Exception of type 'UnityEditor.Build.BuildFailedException' was thrown.
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, System.Exception ex) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:353)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:197)
```

</details>

<details><summary>エラー4（クリックで展開）</summary>

```text
Build completed with a result of 'Failed' in 443 seconds (443240 ms)
UnityEngine.GUIUtility:ProcessEvent (int,intptr) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:197)
```

</details>

<details><summary>エラー5（クリックで展開）</summary>

```text
UnityEditor.BuildPlayerWindow+BuildMethodException: 4 errors
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002b3] in /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPlayerWindowBuildMethods.cs:194 
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPlayerWindowBuildMethods.cs:95 
UnityEngine.GUIUtility:ProcessEvent (int,intptr) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:197)
```

</details>

:::




# 原因
重要ポイントは**太字**にしています．

原因１：`ProjectSettings > Player > Identification`の，`Target API Level`を見てください．
<img width=700px src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/efa6e814-ed7b-8590-ed0f-dc33ba2a6ce7.png">
見ての通り，**`Automatic (highest installed)`になっています**．

::: note
`Minumum API Level`と`Target API Level`の違いについては，
https://hirokuma.blog/?p=2894#toc1
を参考にされることをお勧めします．
:::

原因２：

https://docs.unity3d.com/ja/2023.2/Manual/android-gradle-overview.html

に，以下のような表があります．
![img5.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/e6199580-c265-df5e-3456-8e6620ec5fba.png)
見ての通り，**Unity2019.4 だと， Gradle5.1.1　が入っています**．

# 解決に向けてあと一歩
解決のためのヒントとなったのは，この記事．

https://qiita.com/warapuri/items/17721b113be8c44e5369#%E5%AF%BE%E5%BF%9C%E7%AD%96%EF%BC%92android-build-tools%E3%81%AF%E3%83%90%E3%83%BC%E3%82%B8%E3%83%A7%E3%83%B3300%E3%81%A0%E3%81%91%E3%81%AB%E3%81%99%E3%82%8B

なぜこのサイトに辿り着いたのかは，覚えていませんが，これが大ヒント．
この記事内に，筆者の方が

https://developers.google.com/ar/develop/unity-arf/android-12-build?hl=ja

のリンクを貼ってくださっています．
このリンクによって，全てが解決に向かうのです！

まあ，どういうことかをまとめると，こんな感じです．
説明雑なので，わかる人にはわかりますが，わからない人にはわからないと思います．
ここは読み飛ばしても大丈夫です．
___
(1) そもそも，**Android12 の API Level は31~32**（[参考](https://apilevels.com/)）．
(2) 先ほどのGoogleドキュメントの一部：
>古いバージョンでビルドされた Unity バージョン 2019.4、2020.1、2020.2 では、カスタム Gradle ビルドを Gradle バージョン 6.1.1 以降に設定する必要があります。Android Gradle プラグイン 4.0.1 以降も必要です。

(1)と(2)より，
(3) <ins>**`Android 12 = API Level 31(32) → Gradle 6.1.1 ~` が条件になる．**</ins>

(4) 先ほどの[原因](#原因)１より，`Target API Level`が`Automatic (highest installed)`になっています．
`Highest`と言うぐらいですので，この場合，API Level 33が使用される．
<img width=250px src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/6285fce5-8253-aa9b-11ba-b469daa31e2c.png">

(5) [原因](#原因)２より，Unity2019.4なら，付いてくるのはGradle 5.1.1です．

(3), (4), (5)より，
Unity2019.4（Gradle 5.1.1） だと API Level 33には当然非対応．
　[ 理由 ]
　｜Android 12(API Level 31)の時点で， Unity2019.4(Gradle 5.1.1)は使えない（(3)と(5)より）．
　｜Android 12で Unity2019.4(Gradle 5.1.1)はアウトなのだから，Android 13(API Level 33)は当然アウト．
_____
要するに，
#### 初期状態のUnity2019.4は，API Level 33ビルドができない
ってことです．

# で，結局何すれば良いのか（解決法）
何個か思いつきますが，全部は書きません．簡単にできる2つを紹介します．
* ### 解決法１：確認済 / おすすめ
一番簡単なのは，ビルドする際のエディタのバージョンを変えることです．
先ほどの表をもう一度見てみましょう．
![img5.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2981603/e6199580-c265-df5e-3456-8e6620ec5fba.png)
API Level 33に対応するために，Gradle 6.1.1対応のUnity2020.3.15~のエディタでビルドします．
私は，Unity2020.3.40をインストールしました．
これでビルドしたら，なんも設定せずにすんなりapk作成できました．

* ### 解決法２：未確認
もう一つの方法として，API LevelをUnity2019.4(Gradle5.1.1)でも対応できるLevelまでに落とすことが挙げれらます．しかし，どんなに調べてもGradle5.1.1はどこまでAPI Levelをサポートするのかが分からないため，どこまでLevelを落とすかは，不明です．いつか検証する時がくれば，また更新いたします．
また，最新のAPI Levelではなくなるので，せっかく最新の機器で実行してもパフォーマンスを十分に発揮できない可能性も考えられます．

::: note warn
その他のデメリット：PlayStoreに出すためのAPI Levelの制限等があるので，解決法２だと設定や今後のアップデートによっては，PlayStoreとかに出せなくなる可能性があります．そのため，解決法1をお勧めします．
:::

# まとめ
Unity（特に2019.4）のAndroidビルドにおいて，`More than one file was found with OS independent path...`や`CommandInvokationFailure...`などのエラーが発生した場合は，**上バージョンのUnity（指定した`Target API Level`に対応するGradleをもつバージョン）をインストールし（容量がもったいないとか言っている場合ではなく），再度ビルドする**ことを試してみてください．
※もちろん，この方法で問題が解決するのは一部の方です．これで解決しなければ，また違う問題が発生していると思われます．

本記事は，推敲とかしていないため，誤情報が含まれている可能性大です（そもそも，自分の理解が間違っているかも）．誤情報がありましたら，コメントでお知らせいただけると幸いです．


# 2024/07/09追記
よく見たら，エラー箇所に
```
Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.1.1/userguide/command_line_interface.html#sec:command_line_warnings
```
ありました．ちゃんとエラー読めってことでしたね．