1. Call Java methods through C#:
Add some code to call in C# and use some interfaces provided by Unity to call Java!
private const string JAVA_CLASS_Name = "com."; private void CallJavaFunc(string javaFuncName, params object[] args) { try { //Get Android JavaClass, I don't know why this class is called here. using (AndroidJavaClass jc = new AndroidJavaClass(JAVA_CLASS_Name)) { //Get Activity using (AndroidJavaObject jo = <AndroidJavaObject>("currentActivity")) { //Calling Java methods (javaFuncName, args); } } } catch ( ex) { ("callSdk error:" + ); } } //CYou can use this method to call Java methods in # public void Test1() { int num = 1; CallJavaFunc("JavaFuncName", num); }
In Java, the main thing is to add the called method. The method name is the string parameter (JavaFuncName) above, and the parameters need to correspond one by one!
public class MainActivity extends UnityPlayerActivity { public void JavaFuncName(final int num) { ("C#JavaFuncName is called, parameter num:",(num)); } }
I am an Android project created using eclipse. The activity in java needs to inherit the UnityPlayerActivity. Inheriting this activity requires filling in your android and adding a package. This package is in:
Under the installation path of your Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Release\C lasses,
This way you can call Java methods!
2. Call C# methods through Java:
Add some code to call in Java. Java calls C# mainly through the UnitySendMessage party in the package encapsulated by Unity
Method pass parameter implementation, because this method can only pass one parameter to the C# method, so you can use json when passing multiple parameters.
//Call public void Test2() { JSONObject pms=new JSONObject(); try { //The parameter can only be referenced, so it is wrapped into a json object ("FuncName","Test2"); ("num",1); } catch (JSONException e) { (); } //Use the send message interface provided by Unity to pass parameters to Unity. //GameObject is the name of an object in Unity. //CSharpFunc is CThe name of the method in # //C#The script is hung on the object GameObject ("GameObject","CSharpFunc",()); }
Add the called method in C#. If multiple parameters are passed, you need to parse the parameters one by one.
// Called public void CSharpFunc(string data) { JsonData json = (data); string num = (string)json["num"]; string name = (string)json["FuncName"]; (("quiltJavaThe method has been called,JavaThe method name is:{0},The parameters are{1}",name,num)); }