Reputation: 1933
For a unity game I need to use libs in android-plugin that will send websocket requests. I found out that I have no idea how make the c# code wait for the async operation in android plugin!
I provide a proof of concept case (with simple http get request) to ask my quesiton the simple way. Here are my code that didnt' work:
package com.example.plug2unity1;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Plug1Class {
static OkHttpClient client = new OkHttpClient();
static String doGetRequest(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static String GetPlug2Text() throws IOException {
String res = "";
try {
res = doGetRequest("http://www.google.com");
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
Unity script will have to call the plugin:
void Start () {
TextMesh txtm = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass("com.example.plug2unity1.Plug1Class");
txtm.text = plugin.CallStatic<string>("GetPlug1Text");
}
Edit:
The question is "not" how to make http call, it is obvious that from c# I can do it, I would like to learn "how c# could wait an async operation result from plugin, being it an http call or an I/O operation, same way we do by "promises" in javascript.
Result:
My TextMesh does not change the text, while if I do a POC without any async in plugin side, it works. How could I get this to work?
Upvotes: 0
Views: 1155
Reputation: 125435
Use a callback to do this. Call the Java unction from C#. In the Java function, start new Thread to perform that task. When that task has finished, do a callback from Java to C# to let you know that the task has finished.
C# sample code:
void makeRequestOnJava()
{
TextMesh txtm = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass("com.example.plug2unity1.Plug1Class");
txtm.text = plugin.CallStatic<string>("GetPlug1Text");
}
//Will be called from C# when the request is done
void OnRequestFinished()
{
}
Then on the Java side when your task has finished, use UnityPlayer.UnitySendMessage
to call the OnRequestFinished
function on the C# side.
UnityPlayer.UnitySendMessage("GameObjectName", "OnRequestFinished", null);
You can see how to setup and use the UnityPlayer.UnitySendMessage
function here.
Upvotes: 1