Interaction between Unity and Android (2) - common interaction methods

AndroidJavaClass/AndroidJavaObject is commonly used to implement C# to call Java code, and UnitySendMessage is commonly used to implement Java to call C# code.

【Call code example】

The Java code is:

package com.test.addtest;

import com.unity3d.player.UnityPlayer;

public class JavaTestClass {
    public static int num;
    public static void Add(int a,int b)
    {
        int result = a+b;
        SendMessage(Integer.toString(result));
    }

    private static void SendMessage(final String info)
    {
        UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UnityPlayer.UnitySendMessage("GameBase","U3dCallbackMessage",info);
            }
        });
    }

    public String name;
    public int Sub(int c)
    {
        return num-c;
    }
}

The C# code is:

using UnityEngine;
using UnityEngine.UI;

public class TestCode : MonoBehaviour
{
    public Text text;

    public void Add()
    {
        using (AndroidJavaClass testClass = new AndroidJavaClass("com.test.addtest.JavaTestClass"))
        {
            testClass.CallStatic("Add", 3, 5);
            testClass.SetStatic<int>("num", 10);
            int num = testClass.GetStatic<int>("num");
            U3dCallbackMessage(num.ToString());
            using (AndroidJavaObject testObject = new AndroidJavaObject("com.test.addtest.JavaTestClass"))
            {
                testObject.Set<string>("name", "永恒之星");
                string name = testObject.Get<string>("name");
                U3dCallbackMessage(name);
                int result= testObject.Call<int>("Sub", 8);
                U3dCallbackMessage(result.ToString());
            }
        }
    }

    public void U3dCallbackMessage(string message)
    {
        text.text += message;
        text.text += " ";
    }
}

The result is:

[Analysis of calling process]

  1. After clicking the Button, the Add method is executed. In the Add method, a testClass class is generated with AndroidJavaClass. The incoming parameter is the package name + class name (you can see the Java code), which is similar to the namespace + class name in C#. In this way, we get the class written in Java, but in C#, we have the class directly.
  2.  testClass.CallStatic("Add", 3, 5); This is calling the Add method in JavaTestClass. Add is a static method, which is called by using the CallStatic method of AndroidJavaClass. The first parameter is the method name, and the subsequent parameters are the Add method Parameters, if the Add method has three parameters, obviously there must be three parameters after the method name.
  3. In the Add method, the UnityPlayer.UnitySendMessage method is actually called to pass the result to the C# side. It has three parameters. The first parameter is the name of the GameObject, the second parameter is the method name, and the third parameter is the content of the message. Each parameter is of string type (As for why the RunOnUiThread method is used, it will be explained in the following article. You can first think that this is an asynchronous call, so the result 8 is displayed at the end)
  4. testClass.SetStatic<int>("num", 10) sets the value of the static int type field num in the Java code to 10, int num = testClass.GetStatic<int>("num") gets the int type field in the Java code The value of num, which results in 10
  5. AndroidJavaObject testObject = new AndroidJavaObject("com.test.addtest.JavaTestClass") is to instantiate a Java class.
  6. testObject.Set<string>("name", "Eternal Star"); Set the value for the string type field name of the instantiated object, string name = testObject.Get<string>("name") to get the value
  7.  int result= testObject.Call<int>("Sub", 8); is to call the Sub method of the instantiated object, which has a return value of type int.
  8. Using using is to automatically call the Dispose method of AndroidJavaClass and AndroidJavaObject

[ The difference between AndroidJavaClass and AndroidJavaObject ]

When using, understand AndroidJavaClass as a class in C#, and AndroidJavaObject as an instantiated object of this class

【UnitySendMessage】

In order for the U3dCallbackMessage method in TestCode to receive the unwind message from UnityPlayer.UnitySendMessage in Java, the TestCode script must be hung on the GameObject named GameBase. This is the meaning of the first two parameters of UnityPlayer.UnitySendMessage.

[How to generate Java code]

First of all, you need to install Android Studio yourself. The Java code is not much different from C#. It is easy to write, and you can understand it by searching for unclear grammar.

Create an EmptyActivity

Specify PackageName, which will be used in the code

Select the directory structure of Android, right click on the app, and create a new Module

 

 Choose Android Library

 Select Project, open the Unity directory, under the path of Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Variations, according to whether it is il2cpp or mono packaging, continue to select debug or release mode, find classes.jar in the Classes folder, and import it into Java Under the libs folder in the project, right click and select Add as library. The import method is to drag the file directly, or copy the file to the path of the libs folder.

Right-click at addtest->src->main->java->com.test.addtest to create a new JavaClass, and write code in this JavaClass

 After the code is written, click Mark Project or Rebuild Project

The build is successful without reporting an error. Right-click on the outputs and select show in explorer. Note that the build folder appears automatically after the build, and there is no such folder when the project is just created. Build generally does not report errors, but if you are unlucky, various errors will be reported. These errors can be easily resolved by searching.

Unzip the arr file, select the classes.jar file, and rename it to the name you need. This article is named add

Put this file into unity, and the C# code can call the Java code.

 

 Then you can make an Android package and test it on the emulator.

【Possible errors and solutions in Build】

Appeared to refill. . .

Guess you like

Origin blog.csdn.net/enternalstar/article/details/130961339