Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Embedding Godot in Android projects
The Godot Engine can be embedded within Android applications or libraries, allowing developers to augment their projects with the full capabilities of the engine.
The component hosting the embedded engine is responsible for driving the engine lifecycle via its Android APIs. These APIs can also be used to provide bidirectional communication between the host and the embedded Godot instance allowing for greater control over the desired experience.
We showcase how this is done using a sample Android app that embeds the Godot Engine as an Android view, and uses it to render 3D glTF models.
The GLTF Viewer sample app uses an Android RecyclerView component to create a list of glTF items, populated from Kenney's Food Kit pack. When an item on the list is selected, the app's logic interacts with the embedded Godot Engine to render the selected glTF item as a 3D model.
The sample app source code can be found on GitHub. Follow the instructions in its README to build and install it.
Below we break down the steps used to create the GLTF Viewer app.
Avertissement
Only a single instance of the Godot Engine is supported per Android process. You can configure the process the Android Activity runs under using the android:process attribute.
Avertissement
Automatic resizing / orientation configuration events are not supported and may cause a crash. You can disable those events:
By locking to a specific orientation using the android:screenOrientation attribute.
By declaring that the Activity will handle these configuration events using the android:configChanges attribute.
1. Initial setup of the Android app
Note
The Android sample app was created using Android Studio and using Gradle as the build system.
The Android ecosystem provides multiple tools, IDEs, and build systems for creating Android apps so feel free to use what you're familiar with, and update the steps below accordingly.
Set up an Android application project. It may be a brand new empty project, or an existing project
Add the maven dependency for the Godot Android library
If using
gradle, add the following to thedependencysection of the app's gradle build file. Make sure to update<version>to the latest version of the Godot Android library:
implementation("org.godotengine:godot:<version>")
If using
gradle, include the followingaaptOptionsconfiguration under theandroid > defaultConfigsection of the app's gradle build file. Doing so allowsgradleto include Godot's hidden directories when building the app binary.If your build system does not support hidden directories, you can configure the Godot project to not use hidden directories by deselecting Application > Config > Use Hidden Project Data Directory in the Project Settings.
android {
defaultConfig {
// The default ignore pattern for the 'assets' directory includes hidden files and
// directories which are used by Godot projects, so we override it with the following.
aaptOptions {
ignoreAssetsPattern "!.svn:!.git:!.gitignore:!.ds_store:!*.scc:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"
}
...
Create / update the application's Activity that will be hosting the Godot Engine instance. For the sample app, this is MainActivity
The host Activity should implement the GodotHost interface
The sample app uses Fragments to organize its UI, so it leverages GodotFragment, a fragment component provided by the Godot Android library, to automatically host and manage the Godot Engine instance.
private var godotFragment: GodotFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val currentGodotFragment = supportFragmentManager.findFragmentById(R.id.godot_fragment_container) if (currentGodotFragment is GodotFragment) { godotFragment = currentGodotFragment } else { godotFragment = GodotFragment() supportFragmentManager.beginTransaction() .replace(R.id.godot_fragment_container, godotFragment!!) .commitNowAllowingStateLoss() } ...
Note
The Godot Android library provides GodotActivity, an abstract Activity component that can be extended to automatically host and manage the Godot Engine instance.
And the embedded Godot project provides GodotApp,
an implementation of GodotActivity that can be used as a ready standalone Activity
to launch and manage the embedded Godot project in its own separate Activity.
Alternatively, applications can directly create a Godot instance, host, and manage it themselves.
Using GodotHost#getHostPlugins(...), the sample app creates a runtime GodotPlugin instance that's used to send signals to the embedded Godot project scripts.
The runtime
GodotPlugincan also be used by the embedded Godot project scripts to access methods from the host Android project. For more information, see Godot Android plugins.
Add any additional logic that will be used by your application
For the sample app, this includes adding the ItemsSelectionFragment fragment (and related classes), a fragment used to build and show the list of glTF items
Open the
AndroidManifest.xmlfile, and configure the orientation if needed using the android:screenOrientation attributeIf needed, disable automatic resizing / orientation configuration changes using the android:configChanges attribute
<activity android:name=".MainActivity"
android:screenOrientation="fullUser"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout"
android:exported="true">
...
</activity>
2. Create and set up the Godot project
In your Android project root directory, create a
godotdirectoryOpen the Godot Editor and create a Godot project in the
godotdirectory we just created aboveSee the sample app's Godot project for reference
Configure the project settings:
Update the Godot project's orientation to match the one set in the Android project's manifest
Set textures/vram_compression/import_etc2_astc to
true
Configure the project Android export preset:
Within the Godot Editor export window, create a new Android export preset
Enable
Gradle Build > Use Gradle Buildin the Android export presetSet the
Gradle Build > Export FormattoExport AARSet the
Export Pathfor the generatedAARto a location accessible by the Android project. The exported projectAARbinaries will be used as a build dependency for the Android project.Update the
Architecturesoptions to match the architectures supported by the Android projectFor this sample, we are not planning to use the
GodotAppAndroid Activity provided by the Godot project, so we disablePackage > Show in App LibraryConfigure any other export options that makes sense for your project, then close the export window
Update the Godot project script as needed
For the sample app, the script logic queries for the registered
GodotPlugininstance, and uses it to connect to signals fired by the app logicThe app logic emits a signal every time an item is selected in the list. The signal contains the filepath of the glTF model, which is used by the script logic to render the model.
extends Node3D # Reference to the gltf model that's currently being shown. var current_gltf_node: Node3D = null func _ready(): # Default asset to load when the app starts. _load_gltf("res://gltfs/food_kit/turkey.glb") var app_plugin = Engine.get_singleton("AppPlugin") if app_plugin: print("App plugin is available") # Signal fired from the app logic to update the gltf model being shown. app_plugin.connect(&"show_gltf", _load_gltf) else: print("App plugin is not available") # Load the gltf model specified by the given path. func _load_gltf(gltf_path: String): if current_gltf_node != null: remove_child(current_gltf_node) current_gltf_node = load(gltf_path).instantiate() add_child(current_gltf_node)
3. Compiler et exécuter l'application
Now that the Godot project is set up, the next step is complete the configuration of the Android project's dependencies.
We need to add dependencies to the AAR binaries generated by the Godot project export process:
Add the following to the
dependencysection of the app's gradle build file, where<godot_project_export_path>points to the Godot project's export directory:implementation fileTree(dir: "<godot_project_export_path>", include: ["**/*.jar", "**/*.aar"])
The export Godot project AAR binaries have dependencies on the androidx-fragment and androidx-core-splashscreen libraries, so they need to be included in the Android project dependencies as well.
Add the following to the
dependencysection of the app's gradle build file:implementation "androidx.core:core-splashscreen:1.2.0" implementation "androidx.fragment:fragment:1.9.1"
The final step is to configure the build flow, such that the Godot project is built and exported every time the sample app is built. To do so, add the following code snippet to the app's gradle build file:
def godotBinary = "<absolute_path_to_godot_binary>" tasks.register("exportGodotProject", Exec) { doFirst { if (godotBinary.isEmpty()) { throw new GradleException("The path to the Godot editor binary was not specified.") } File godotBinaryFile = new File(godotBinary) if (!godotBinaryFile.exists()) { throw new GradleException("The path to the Godot editor binary is invalid: $godotBinary") } } description = "Export the embedded Godot project" workingDir file("<path_to_godot_project>") executable godotBinary args "--headless", "--export-release", "<android_export_preset_name>", "<export_path_relative_to_workingDir>" } afterEvaluate { tasks.named("preBuild").configure { dependsOn("exportGodotProject") } }
Où :
<absolute_path_to_godot_binary>is the absolute path to the Godot editor binary<path_to_godot_project>is the path to the Godot project<android_export_preset_name>is the name of the Android export preset configured in the Godot project<export_path_relative_to_workingDir>is theExport Pathconfigured in the Godot project relative to the project path or absolute
Once this is completed, build and run the Android app. If set up correctly, the host Activity will initialize the Godot Engine on startup, and run the embedded Godot project.
While the app is running on device, you can check Android logcat to investigate any errors or crashes.
For reference, check the build and install instructions for the GLTF Viewer sample app.