Code examples: Call Java/Kotlin code from C# scripts
Refer to the code examples for integrating Java/Kotlin functionality in your Unity project.
Read time 2 minutesLast updated 6 days ago
Unity provides high-level APIs such as , , , and that allow you to interact with Java/Kotlin code from C# scripts.
AndroidJavaObjectAndroidJavaClassAndroidJavaProxyAndroidApplicationThe following code examples demonstrate how to use these APIs.
Example 1: Get the hash code for a Java string
The following code example creates an instance of java.lang.String initialized with a string, and retrieves the hash value for that string.
using UnityEngine;public class JavaExamples{ public static int GetJavaStringHashCode(string text) { using (AndroidJavaObject jo = new AndroidJavaObject("java.lang.String", text)) { int hash = jo.Call<int>("hashCode"); return hash; } }}
This example:
- Creates an that represents a java.lang.String.
AndroidJavaObject - The constructor takes at least one parameter, which is the name of the class to construct an instance of. Any parameters after the class name are for the constructor call on the object, in this case the
AndroidJavaObjectparameter fromtext.GetJavaStringHashCode - Calls hashCode() to get the hash code of the string. This call uses the generic type parameter for
intbecauseCallreturns the hash code as an integer.hashCode()
Example 2: Retrieve the application's cache directory
The following code example retrieves the cache directory for the current application in C# using the class.
AndroidApplicationusing UnityEngine;using UnityEngine.Android;public class JavaExamples{ public static string GetApplicationCacheDirectory() { using var javaFile = AndroidApplication.currentActivity.Call<AndroidJavaObject>("getCacheDir"); var cacheDirectory = javaFile.Call<string>("getCanonicalPath"); return cacheDirectory; }}
This example:
- Uses to access the current Android activity, without explicitly creating
AndroidApplication.currentActivityorAndroidJavaClassinstances.AndroidJavaObject - Calls getCacheDir() on the Activity object, which returns a File object that represents the cache directory.
- Calls getCanonicalPath() on the File object can to get the cache directory as a string.