Integration Unity as a library in native Android app Version 2

This document explains how to include Unity as a Library into standard Android application through Activity. You can read more about Unity as a Library.

This example address Version 1 issues of example, most important one relates to unloading/quitting Unity.

Pre Requirements:

  • Android Studio 3.4.2+
  • Unity version 2019.3.0b4+

1. Get source

  • Clone or Download GitHub repo uaal-example. It includes:
    4584565--427066--image8.png

  • Unityproject - this is a simple demo project made with Unity which will be integrated to the standard Android application. OverrideUnityActivity class in Assets/Plugins/Android extends UnityPlayerActivity

  • NativeAndroidApp - this is the Basic Activity application from Android Studio templates where Unity project will be integrated. It has a simple UI, MainUnityActivity, which extends OverrideUnityActivity, and is prepared to start MainUnityActivity with an Intent

2. Generate gradle project for Android platform

  • Open UnityProject in Unity Editor

  • Go to Build Settings window (Menu / File / Build Settings)

  • Select and switch to Android Platform

  • Select option “Export Project”

  • Export UnityProject to androidBuild folder, the folder structure should look like this:4584565--427075--image10.png

2 Likes

3. Add Unity Library module to NativeAndroidApp
Do the following to add the exported androidBuild/unityLibrary module to the NativeAndroidApp gradle project in Android Studio:

  • Open NativeAndroidApp in Android Studio

  • Open settings.gradle file

  • Add a new project pointing to unityLibrary module at the end of the file:

include ':unityLibrary'
project(':unityLibrary').projectDir=new File('..\\UnityProject\\androidBuild\\unityLibrary')

  • Open build.gradle(Module: app) file

  • Add the following in dependencies{ block

implementation project(':unityLibrary')
implementation fileTree(dir: project(':unityLibrary').getProjectDir().toString() + ('\\libs'), include: ['*.jar'])

  • Open build.gradle(Project: NativeAndroidApp) file

  • Add the following in allprojects{repositories{ block

flatDir {
    dirs "${project(':unityLibrary').projectDir}/libs"
}

1 Like

Project is ready
Everything is ready to build, run and debug:

If everything succeeded, at this point you should be able to run NativeAndroidApp:


Important note:

  • Unity is running in another process android: process=“:Unity” (AndroidManifest.xml at app module)
  • After installation there will be two icons added on the device. To leave only the icon of the main activity, remove … from the AndroidManifest.xml in unityLibrary
  • (Optional) We found some Android 7.* devices set frontOfTask to wrong state for activities as a result when finishing/quitting Unity activity whole task goes to background instead of bringing back Main activity. Next workaround keeps expected behavior: add to MainUnityActivity.java from NativeAndroidApp
@Override public void onUnityPlayerQuitted() { showMainActivity(""); finish(); }

Full Project
If you have issues following integration steps you can try out fully prepared project ready to build and deploy: Download & Uncompress Full Uaal Example Android project, then open NativeAndroidApp in Android Studio.

3 Likes

Looks like the way the unloading/quitting issues were addressed is by having Unity run in a separate process and explicitly killing it.

This was the workaround that my team had investigated but ultimately our client is unwilling to operate with the JVM split into multiple processes. This is because they use Android UI elements over the Unity view that need to access the objects from the app’s memory. To continue doing this, they would need to replicate their main process memory in the Unity process.

Ultimately we found other workarounds to use Unity in the same process but workarounds are not what we like to ship in production code. Will there be any solution (like tightening up Unity’s shut-down sequence) for apps that cannot be split?

5 Likes

IUnityPlayerLifecycleEvents introduced since 2019.3.b4+ provides easy way to react to two important lifecycle events of Unity Player:

  • Unload - IUnityPlayerLifecycleEvents.onUnityPlayerUnloaded will be called when unity player will be unloaded though Application.Unload or UnityPlayer.unload(). (UnityPlayer in unloaded/paused state atm.)

  • Quit - IUnityPlayerLifecycleEvents.onUnityPlayerQuitted is called when Unity player did quit. Please note process where unity was running will be killed after this call.

You can pass instance of IUnityPlayerLifecycleEvents to UnityPlayer constructor or override methods in subclasses of UnityPlayer or UnityPlayerActivity

@btristan you can try keep activity in same process and relay on Unload

@PavelLU Would you be able to provide the steps required to make a 2019.3.b1-3 project compliant with b4+ build?

This all is exactly what I was looking for! I’m working on making an Android AR function into my native android app using Unity as a Library. However, when I import the ARCore package in the example app it immediately crashes. Do I need to enable anything in the standard Android app provided to get AR working?

2019-10-01 13:07:53.189 10682-10682/com.unity.mynativeapp:Unity E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.unity.mynativeapp:Unity, PID: 10682
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.unity.mynativeapp-6EhPtngHs603UwkTWPvsew==/base.apk"],nativeLibraryDirectories=[/data/app/com.unity.mynativeapp-6EhPtngHs603UwkTWPvsew==/lib/arm64, /data/app/com.unity.mynativeapp-6EhPtngHs603UwkTWPvsew==/base.apk!/lib/arm64-v8a, /system/lib64]]] couldn't find "libmain.so"
        at java.lang.Runtime.loadLibrary0(Runtime.java:1012)
        at java.lang.System.loadLibrary(System.java:1669)
        at com.unity3d.player.UnityPlayer.<clinit>(Unknown Source:13)
        at com.unity3d.player.UnityPlayerActivity.onCreate(UnityPlayerActivity.java:41)
        at com.company.product.OverrideUnityActivity.onCreate(OverrideUnityActivity.java:16)
        at com.unity.mynativeapp.MainUnityActivity.onCreate(MainUnityActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:7326)
        at android.app.Activity.performCreate(Activity.java:7317)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3072)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3235)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6986)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

I tried with both AR Foundation + ARCore through package manager and the ARCore provided as a .unitypackage. Both make the unity part of the app crash instantly, even when I’m not using anything of it yet. Just having it in htere makes it crash.

I’m getting the same error …

I got it working! I had to enable Player > Configuration > Scripting Backend to IL2CPP and Player > Configuration > Target Architectures > ARM64.

2 Likes

Using Unity project in this thread with Unity2019.3.0b5, I could compile it to Android, IL2CPP, ARM64.

But when I include Vuforia to the project I get compilation errors:

IL2CPP error for type ‘UnityEngine.Experimental.Rendering.RenderPipeline’ in assembly ‘D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Temp\StagingArea\assets\bin\Data\Managed\UnityEngine.dll’
Additional information: Exception has been thrown by the target of an invocation.

Failed running C:\Program Files\Unity\Hub\Editor\2019.3.0b5\Editor\Data\il2cpp/build/il2cpp.exe --convert-to-cpp --emit-null-checks --enable-array-bounds-check --dotnetprofile=“unityaot” --compile-cpp --libil2cpp-static --platform=“Android” --architecture=“ARM64” --configuration=“Release” --outputpath=“D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Temp\StagingArea\assets\bin\Data\Native\arm64-v8a\libil2cpp.so” --cachedirectory=“D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Assets..\Library\il2cpp_android_arm64-v8a/il2cpp_cache” --additional-include-directories=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/PlaybackEngines/AndroidPlayer/Tools\bdwgc/include” --additional-include-directories=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/PlaybackEngines/AndroidPlayer/Tools\libil2cpp/include” --tool-chain-path=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/PlaybackEngines/AndroidPlayer/NDK” --profiler-report --map-file-parser=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/Tools/MapFileParser/MapFileParser.exe” --directory=D:/Public/AndroidStudio/HoodooSDKtest/UnityProject/Temp/StagingArea/assets/bin/Data/Managed --generatedcppdir=D:/Public/AndroidStudio/HoodooSDKtest/UnityProject/Temp/StagingArea/Il2Cpp/il2cppOutput

stdout:
IL2CPP error for type ‘UnityEngine.Experimental.Rendering.RenderPipeline’ in assembly ‘D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Temp\StagingArea\assets\bin\Data\Managed\UnityEngine.dll’
Additional information: Exception has been thrown by the target of an invocation.
il2cpp.exe didn’t catch exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.NullReferenceException: Object reference not set to an instance of an object.
at Unity.IL2CPP.ErrorInformation.set_Method(MethodDefinition value)
at Unity.IL2CPP.GenericsCollection.GenericContextFreeVisitor.Visit(MethodDefinition methodDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(EventDefinition eventDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(TypeDefinition typeDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(ModuleDefinition moduleDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(AssemblyDefinition assemblyDefinition, Context context)
— End of inner exception stack trace —
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[ ] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[ ] parameters, Object[ ] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[ ] parameters, CultureInfo culture)
at Unity.Cecil.Visitor.Visitor.Visit[T](T node, Context context)
at Unity.IL2CPP.GenericsCollection.GenericsCollector.CollectPerAssembly(AssemblyDefinition assembly)
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at Unity.IL2CPP.GenericsCollection.GenericsCollector.MergeCollections(IEnumerable1 collections)
at Unity.IL2CPP.AssemblyConverter.Apply()
at Unity.IL2CPP.AssemblyConverter.ConvertAssemblies(IEnumerable1 assemblyDirectories, IEnumerable1 explicitAssemblies, NPath outputDir, NPath dataFolder, NPath symbolsFolder, NPath executableAssembiesFolder, NPath monoLibFolder, NPath monoEtcFolder, NPath[ ] searchDirectories, String entryAssemblyName, NPath[ ] extraTypesFiles)
at il2cpp.Program.DoRun(String[ ] args, List`1 foundAssemblies)
at il2cpp.Program.Run(String[ ] args, Boolean setInvariantCulture)
at il2cpp.Program.Main(String[ ] args)
stderr:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.NullReferenceException: Object reference not set to an instance of an object.
at Unity.IL2CPP.ErrorInformation.set_Method(MethodDefinition value)
at Unity.IL2CPP.GenericsCollection.GenericContextFreeVisitor.Visit(MethodDefinition methodDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(EventDefinition eventDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(TypeDefinition typeDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(ModuleDefinition moduleDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(AssemblyDefinition assemblyDefinition, Context context)
— End of inner exception stack trace —
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[ ] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[ ] parameters, Object[ ] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[ ] parameters, CultureInfo culture)
at Unity.Cecil.Visitor.Visitor.Visit[T](T node, Context context)
at Unity.IL2CPP.GenericsCollection.GenericsCollector.CollectPerAssembly(AssemblyDefinition assembly)
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at Unity.IL2CPP.GenericsCollection.GenericsCollector.MergeCollections(IEnumerable1 collections)
at Unity.IL2CPP.AssemblyConverter.Apply()
at Unity.IL2CPP.AssemblyConverter.ConvertAssemblies(IEnumerable1 assemblyDirectories, IEnumerable1 explicitAssemblies, NPath outputDir, NPath dataFolder, NPath symbolsFolder, NPath executableAssembiesFolder, NPath monoLibFolder, NPath monoEtcFolder, NPath[ ] searchDirectories, String entryAssemblyName, NPath[ ] extraTypesFiles)
at il2cpp.Program.DoRun(String[ ] args, List`1 foundAssemblies)
at il2cpp.Program.Run(String[ ] args, Boolean setInvariantCulture)
at il2cpp.Program.Main(String[ ] args)

UnityEngine.Debug:LogError(Object)
UnityEditorInternal.Runner:RunProgram(Program, String, String, String, CompilerOutputParserBase)
UnityEditorInternal.Runner:RunManagedProgram(String, String, String, CompilerOutputParserBase, Action1) UnityEditorInternal.IL2CPPBuilder:RunIl2CppWithArguments(List1, Action1, String) UnityEditorInternal.IL2CPPBuilder:ConvertPlayerDlltoCpp(Il2CppBuildPipelineData, String, String, Boolean) UnityEditorInternal.IL2CPPBuilder:Run() UnityEditorInternal.IL2CPPUtils:RunIl2Cpp(String, String, IIl2CppPlatformProvider, Action1, RuntimeClassRegistry)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Exception: C:\Program Files\Unity\Hub\Editor\2019.3.0b5\Editor\Data\il2cpp/build/il2cpp.exe did not run properly!
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at <52c46852ed4749ed926125cda2005635>:0)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action1[T] setupStartInfo) (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPBuilder.RunIl2CppWithArguments (System.Collections.Generic.List1[T] arguments, System.Action1[T] setupStartInfo, System.String workingDirectory) (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPBuilder.ConvertPlayerDlltoCpp (UnityEditor.Il2Cpp.Il2CppBuildPipelineData data, System.String outputDirectory, System.String workingDirectory, System.Boolean platformSupportsManagedDebugging) (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPBuilder.Run () (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at <52c46852ed4749ed926125cda2005635>:0)
UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <7a3206746c744c65a3137ccfd4678266>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <7a3206746c744c65a3137ccfd4678266>: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 <7a3206746c744c65a3137ccfd4678266>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <7a3206746c744c65a3137ccfd4678266>: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 <52c46852ed4749ed926125cda2005635>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Build completed with a result of ‘Failed’
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

UnityEditor.BuildPlayerWindow+BuildMethodException: 4 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x00275] in <52c46852ed4749ed926125cda2005635>:0
at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <52c46852ed4749ed926125cda2005635>:0
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Hi, I have issues trying to build a Android build, tried it on emulator and on phone. But it always crashes when I clicked Open in Unity. The thing is there is no error at all in the Android Studio’s logcat and build logs.

Anyone knows what’s happening? It even happens with the full build that is “completed”

1 Like

Can you please check if you can Build & Run your project with Vuforia to phone directly from Unity, (don’t do any integration to native steps)

Can someone check if unity default videoplayer component plays when added to ar when unity is built as a library? Ive just ported my unity app as a library( my app uses a plane to play a video when a marker is detected). If i build it as a unity app and install it works ok. But if i include as library the plane shows but not video or audio is played…

2 Likes

Same error when building an apk ( IL2CPP, .net 4 or 2, ARM64):

IL2CPP error for type ‘UnityEngine.Experimental.Rendering.RenderPipeline’ in assembly ‘D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Temp\StagingArea\assets\bin\Data\Managed\UnityEngine.dll’
Additional information: Exception has been thrown by the target of an invocation.

Failed running C:\Program Files\Unity\Hub\Editor\2019.3.0b5\Editor\Data\il2cpp/build/il2cpp.exe --convert-to-cpp --emit-null-checks --enable-array-bounds-check --dotnetprofile=“unityaot” --compile-cpp --libil2cpp-static --platform=“Android” --architecture=“ARM64” --configuration=“Release” --outputpath=“D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Temp\StagingArea\assets\bin\Data\Native\arm64-v8a\libil2cpp.so” --cachedirectory=“D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Assets..\Library\il2cpp_android_arm64-v8a/il2cpp_cache” --additional-include-directories=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/PlaybackEngines/AndroidPlayer/Tools\bdwgc/include” --additional-include-directories=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/PlaybackEngines/AndroidPlayer/Tools\libil2cpp/include” --tool-chain-path=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/PlaybackEngines/AndroidPlayer/NDK” --profiler-report --map-file-parser=“C:/Program Files/Unity/Hub/Editor/2019.3.0b5/Editor/Data/Tools/MapFileParser/MapFileParser.exe” --directory=D:/Public/AndroidStudio/HoodooSDKtest/UnityProject/Temp/StagingArea/assets/bin/Data/Managed --generatedcppdir=D:/Public/AndroidStudio/HoodooSDKtest/UnityProject/Temp/StagingArea/Il2Cpp/il2cppOutput

stdout:
IL2CPP error for type ‘UnityEngine.Experimental.Rendering.RenderPipeline’ in assembly ‘D:\Public\AndroidStudio\HoodooSDKtest\UnityProject\Temp\StagingArea\assets\bin\Data\Managed\UnityEngine.dll’
Additional information: Exception has been thrown by the target of an invocation.
il2cpp.exe didn’t catch exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.NullReferenceException: Object reference not set to an instance of an object.
at Unity.IL2CPP.ErrorInformation.set_Method(MethodDefinition value)
at Unity.IL2CPP.GenericsCollection.GenericContextFreeVisitor.Visit(MethodDefinition methodDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(EventDefinition eventDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(TypeDefinition typeDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(ModuleDefinition moduleDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(AssemblyDefinition assemblyDefinition, Context context)
— End of inner exception stack trace —
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[ ] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[ ] parameters, Object[ ] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[ ] parameters, CultureInfo culture)
at Unity.Cecil.Visitor.Visitor.Visit[T](T node, Context context)
at Unity.IL2CPP.GenericsCollection.GenericsCollector.CollectPerAssembly(AssemblyDefinition assembly)
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at Unity.IL2CPP.GenericsCollection.GenericsCollector.MergeCollections(IEnumerable1 collections)
at Unity.IL2CPP.AssemblyConverter.Apply()
at Unity.IL2CPP.AssemblyConverter.ConvertAssemblies(IEnumerable1 assemblyDirectories, IEnumerable1 explicitAssemblies, NPath outputDir, NPath dataFolder, NPath symbolsFolder, NPath executableAssembiesFolder, NPath monoLibFolder, NPath monoEtcFolder, NPath[ ] searchDirectories, String entryAssemblyName, NPath[ ] extraTypesFiles)
at il2cpp.Program.DoRun(String[ ] args, List`1 foundAssemblies)
at il2cpp.Program.Run(String[ ] args, Boolean setInvariantCulture)
at il2cpp.Program.Main(String[ ] args)
stderr:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.NullReferenceException: Object reference not set to an instance of an object.
at Unity.IL2CPP.ErrorInformation.set_Method(MethodDefinition value)
at Unity.IL2CPP.GenericsCollection.GenericContextFreeVisitor.Visit(MethodDefinition methodDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(EventDefinition eventDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(TypeDefinition typeDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(ModuleDefinition moduleDefinition, Context context)
at Unity.Cecil.Visitor.Visitor.Visit(AssemblyDefinition assemblyDefinition, Context context)
— End of inner exception stack trace —
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[ ] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[ ] parameters, Object[ ] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[ ] parameters, CultureInfo culture)
at Unity.Cecil.Visitor.Visitor.Visit[T](T node, Context context)
at Unity.IL2CPP.GenericsCollection.GenericsCollector.CollectPerAssembly(AssemblyDefinition assembly)
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at Unity.IL2CPP.GenericsCollection.GenericsCollector.MergeCollections(IEnumerable1 collections)
at Unity.IL2CPP.AssemblyConverter.Apply()
at Unity.IL2CPP.AssemblyConverter.ConvertAssemblies(IEnumerable1 assemblyDirectories, IEnumerable1 explicitAssemblies, NPath outputDir, NPath dataFolder, NPath symbolsFolder, NPath executableAssembiesFolder, NPath monoLibFolder, NPath monoEtcFolder, NPath[ ] searchDirectories, String entryAssemblyName, NPath[ ] extraTypesFiles)
at il2cpp.Program.DoRun(String[ ] args, List`1 foundAssemblies)
at il2cpp.Program.Run(String[ ] args, Boolean setInvariantCulture)
at il2cpp.Program.Main(String[ ] args)

UnityEngine.Debug:LogError(Object)
UnityEditorInternal.Runner:RunProgram(Program, String, String, String, CompilerOutputParserBase)
UnityEditorInternal.Runner:RunManagedProgram(String, String, String, CompilerOutputParserBase, Action1) UnityEditorInternal.IL2CPPBuilder:RunIl2CppWithArguments(List1, Action1, String) UnityEditorInternal.IL2CPPBuilder:ConvertPlayerDlltoCpp(Il2CppBuildPipelineData, String, String, Boolean) UnityEditorInternal.IL2CPPBuilder:Run() UnityEditorInternal.IL2CPPUtils:RunIl2Cpp(String, String, IIl2CppPlatformProvider, Action1, RuntimeClassRegistry)
UnityEngine.GUIUtility:processEvent(Int32, IntPtr)

Exception: C:\Program Files\Unity\Hub\Editor\2019.3.0b5\Editor\Data\il2cpp/build/il2cpp.exe did not run properly!
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at <52c46852ed4749ed926125cda2005635>:0)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action1[T] setupStartInfo) (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPBuilder.RunIl2CppWithArguments (System.Collections.Generic.List1[T] arguments, System.Action1[T] setupStartInfo, System.String workingDirectory) (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPBuilder.ConvertPlayerDlltoCpp (UnityEditor.Il2Cpp.Il2CppBuildPipelineData data, System.String outputDirectory, System.String workingDirectory, System.Boolean platformSupportsManagedDebugging) (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPBuilder.Run () (at <52c46852ed4749ed926125cda2005635>:0) UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at <52c46852ed4749ed926125cda2005635>:0)
UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <7a3206746c744c65a3137ccfd4678266>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <7a3206746c744c65a3137ccfd4678266>: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 <7a3206746c744c65a3137ccfd4678266>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <7a3206746c744c65a3137ccfd4678266>: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 <52c46852ed4749ed926125cda2005635>:0)
UnityEngine.GUIUtility:processEvent(Int32, IntPtr)

Build completed with a result of ‘Failed’
UnityEngine.GUIUtility:processEvent(Int32, IntPtr)

UnityEditor.BuildPlayerWindow+BuildMethodException: 4 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x00275] in <52c46852ed4749ed926125cda2005635>:0
at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <52c46852ed4749ed926125cda2005635>:0
UnityEngine.GUIUtility:processEvent(Int32, IntPtr)

Is there any settings that the guide above is missing? I’ve followed the guide step by step and I’ve checked it multiple times and still it crashes on clicking the Open Unity within the app.

Seems like there may be a step missing around how you incorporate the OverrideUnityActivity into the native app. The example implementation works but I can’t discern a difference between that and my custom attempt.

1 Like

The example project extends OverrideUnityActivity with MainUnityActivity but MainUnityActivity isn’t mentioned in the walkthrough. Some sort of linking/namespacing issue? Hope this helps.

2 Likes

I

I applied AR Foundation. My app crushes when I open the Unity window in native android app. Does anyone know the reason why?

same issue. I just applied AR foundation to the example project they have and build it again. The unity window crashes in native app.

Did you enable Player > Configuration > Scripting Backend to IL2CPP and Player > Configuration > Target Architectures > ARM64 ?