- Home /
Accessing Java class from C# script
I am developing for Android and wanted to create a UUID using Java library. Believing this can only done by using platform functionalities directly. I wrote: AndroidJavaClass javaUUID = new AndroidJavaClass("java.util.UUID"); string uID = javaUUID.Call ("randomUUID"); EditorUtility.DisplayDialog("ID",uID,"OK");
This code fails with error:
JNI: Init'd AndroidJavaClass with null ptr!
A more general problem is of course to find out when to use Unity facilities and when that is not enough and you have to call platform methods from your script.
Answer by Bunny83 · Dec 12, 2018 at 04:29 AM
I'm not sure if you can actually use the class but it seems it should be available. However there are some issues here. First of all you haven't mentioned on which line it fails.
Anyways this line can never work:
string uID = javaUUID.Call("randomUUID");
First of all you have to use CallStatic since this is a static method. Call only work on instances. The second issue is that randomUUID returns an UUID object and not a string. So you can not assign the return value to a C# string.
You would need to do something like this:
AndroidJavaObject uID = javaUUID.CallStatic("randomUUID");
string uIDStr = uID.Call("toString");
However i'm not sure why you want to use the Java class for this. Mono / .NET has the GUID struct. To generate a new GUID just use the static NewGuid method:
var guid = System.Guid.NewGuid();
Just like in Java the guid is not a string. However it also has a ToString method (like all types in .NET)
string str = guid.ToString();
This fails at the first line. AndroidJavaClass javaUUID = new AndroidJavaClass("java.util.UUID");
I was not able to fix CallStatic() but used System.Guid ins$$anonymous$$d. Will use JavaClass when I have to.