编写Unity2Android核心类代码

这里我们通过Java的反射原理来获取本来导入class.jar类才能引用到的com.unity3d.player.UnityPlayer包下的currentActivity上下文,同理给unity发消息也是反射原理

     package com.jing.unity;
     import android.app.Activity;
     import android.widget.Toast;
     import java.lang.reflect.InvocationTargetException;
     import java.lang.reflect.Method;
      * Created by Jing on 2018-1-18.
     public class Unity2Android {
          * unity项目启动时的的上下文
         private Activity _unityActivity;
          * 获取unity项目的上下文
          * @return
         Activity getActivity(){
             if(null == _unityActivity) {
                 try {
                     Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
                     Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);
                     _unityActivity = activity;
                 } catch (ClassNotFoundException e) {
                 } catch (IllegalAccessException e) {
                 } catch (NoSuchFieldException e) {
             return _unityActivity;
          * 调用Unity的方法
          * @param gameObjectName    调用的GameObject的名称
          * @param functionName      方法名
          * @param args              参数
          * @return                  调用是否成功
         boolean callUnity(String gameObjectName, String functionName, String args){
             try {
                 Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
                 Method method =classtype.getMethod("UnitySendMessage", String.class,String.class,String.class);
                 method.invoke(classtype,gameObjectName,functionName,args);
                 return true;
             } catch (ClassNotFoundException e) {
             } catch (NoSuchMethodException e) {
             } catch (IllegalAccessException e) {
             } catch (InvocationTargetException e) {
             return false;
          * Toast显示unity发送过来的内容
          * @param content           消息的内容
          * @return                  调用是否成功
         public boolean showToast(String content){
             Toast.makeText(getActivity(),content,Toast.LENGTH_SHORT).show();
             //这里是主动调用Unity中的方法,该方法之后unity部分会讲到
             callUnity("Main Camera","FromAndroid", "hello unity i'm android");
             return true;
  • 需要实现其他的Android代码,可以依此添加,Activity从此处获取即可

  • Build,需点击Module,再点击上方Build->RebuildProject即可生成对应aar包

  • Unity

  • 导入aar包,放入Assets/Plugins/Android目录下

  • 编写代码调Android

    /// <summary>
    /// Unity调Android
    /// </summary>
    public void OnBtnClick()
        //通过该API来实例化导入的arr中对应的类
        AndroidJavaObject _ajc = new AndroidJavaObject("com.jing.unity.Unity2Android");
        //通过API来调用原生代码的方法
        bool success = _ajc.Call<bool>("showToast","this is unity");
        if(true == success)
            //请求成功
    /// <summary>
    /// Android调Unity
    /// </summary>
    public void FromAndroid(string content)
        text.text = content;